Download the PHP package rnd-cosoft/api-tools-oauth2 without Composer
On this page you can find all versions of the php package rnd-cosoft/api-tools-oauth2. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download rnd-cosoft/api-tools-oauth2
More information about rnd-cosoft/api-tools-oauth2
Files in rnd-cosoft/api-tools-oauth2
Package api-tools-oauth2
Short Description Laminas module for implementing an OAuth2 server
License BSD-3-Clause
Homepage https://api-tools.getlaminas.org
Informations about the package api-tools-oauth2
api-tools-oauth2
🇷🇺 Русским гражданам
Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.
У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.
Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"
🇺🇸 To Citizens of Russia
We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.
One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.
You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"
Laminas module for OAuth2 authentication.
This module uses the oauth2-server-php library by Brent Shaffer to provide OAuth2 support.
Requirements
Please see the composer.json file.
Installation
You can install using:
If you are using ext/mongodb, you will also need to install a compatibility package:
Finally, you will need to add the following modules to your application's configuration:
laminas-component-installer
If you use laminas-component-installer, that plugin will install api-tools-oauth2 and its other Laminas API Tools dependencies as modules for you.
Configuration
This module uses any PDO-suported database to manage the OAuth2 information
(users, client, token, etc). The database structure is stored in
data/db_oauth2.sql
.
PostgreSQL
We also have a PostgreSQL-specific DDL in
data/db_oauth2_postgresql.sql
.
For security reasons, we encrypt the fields client_secret
(table
oauth_clients
) and password
(table oauth_users
) using the
bcrypt algorithm (via the class
Laminas\Crypt\Password\Bcrypt).
In order to configure the api-tools-oauth2 module for database access, you need to copy
the file config/oauth2.local.php.dist
to config/autoload/oauth2.local.php
in
your Laminas application, and edit it to provide your DB credentials (DNS, username,
password).
We also include a SQLite database in data/dbtest.sqlite
that you can use in a
test environment. In this database, you will find a test client account with
the client_id
"testclient" and the client_secret
"testpass". If you want to
use this database, you can configure your config/autoload/oauth2.local.php
file as follow:
Mongo Configuration
The Mongo OAuth2 adapter wraps the bshaffer adapter by adding the same password encryption as the rest of api-tools. The collections needed are the same as above in the PDO adapter. To create an OAuth2 client, insert a document like the following into the oauth_clients collection:
User ID Provider
When a user requests an authorization code they may provide their user_id as a request parameter to
the /oauth/authorize
route. This will store the user_id
in the access_token
, refresh_token
,
and authorization_code
tables as the user goes throught the oauth2 process.
A user may be authenticated through Laminas\Authentication\AuthenticationService
or another
authentication means. When a user must provide authentication before they may access the
/oauth/authorize
route, the authenticated user ID should be used. This is done with the service
manager alias Laminas\ApiTools\OAuth2\Provider\UserId
.
The default User ID Provider uses the request query parameter user_id
and is handled via the class
Laminas\ApiTools\OAuth2\Provider\UserId\Request
.
Provided with this repository is an alternative provider,
Laminas\ApiTools\OAuth2\Provider\UserId\AuthorizationService
, which uses
Laminas\Authentication\AuthenticationService
to fetch the identity. To change the User ID Provider
to use this service, change the Laminas\ApiTools\OAuth2\Provider\UserId
service alias to point at it:
How to test OAuth2
To test the OAuth2 module, you have to add a client_id
and a client_secret
into the oauth2 database. If you are using the SQLite test database, you don't
need to add a client_id
; just use the default "testclient"/"testpass" account.
Because we encrypt the password using the bcrypt
algorithm, you need to
encrypt the password using the Laminas\Crypt\Password\Bcrypt
class from Laminas. We provided a simple script in /bin/bcrypt.php
to
generate the hash value of a user's password. You can use this tool from the
command line, with the following syntax:
where "testpass" is the user's password that you want to encrypt. The output of the previous command will be the hash value of the user's password, a string of 60 bytes like the following:
After the generation of the hash value of the password (client_secret
), you can
add a new client_id
in the database using the following SQL statement:
To test the OAuth2 module, you can use an HTTP client like HTTPie or CURL. The examples below use HTTPie and the test account "testclient"/"testpass".
REQUEST TOKEN (client_credentials)
You can request an OAuth2 token using the following HTTPie command:
This POST requests a new token to the OAuth2 server using the client_credentials mode. This is typical in machine-to-machine interaction for application access. If everything works fine, you should receive a response like this:
Security note: because this POST uses basic HTTP authentication, the
client_secret
is exposed in plaintext in the HTTP request. To protect this
call, a TLS/SSL
connection is required.
AUTHORIZE (code)
If you have to integrate an OAuth2 service with a web application, you need to use the Authorization Code grant type. This grant requires an approval step to authorize the web application. This step is implemented using a simple form that requests the user approve access to the resource (account). This module provides a simple form to authorize a specific client. This form can be accessed by a browser using the following URL:
This page will render the form asking the user to authorize or deny the access for the client. If they authorize the access, the OAuth2 module will reply with an Authorization code. This code must be used to request an OAuth2 token; the following HTTPie command provides an example of how to do that:
In client-side scenarios (i.e mobile) where you cannot store the Client Credentials in a secure way, you cannot use the previous workflow. In this case we can use an implicit grant. This is similar to the authorization code, but rather than an authorization code being returned from the authorization request, a token is returned.
To enable the module to accept the implicit grant type, you need to change the
configuration of allow_implicit
to true
in the
config/autoload/oauth2.local.php
file:
To request a token from the client side, you need to request authorization via the OAuth2 server:
This request will render the authorization form as in the previous example. If
you authorize the access, the request will be redirected to /oauth/receivecode
(as provided in the redirect_uri
parameter in the above example), with the
access_token
specified in the URI fragment, per the following sample:
To get the access_token
, you can parse the URI. We used the URI fragment to
pass the access_token
because in this way the token is not transmitted to the
server; it will available only to the client.
In JavaScript, you can easily parse the URI with this snippet of code:
REVOKE (code)
Starting with version 1.4.0, you can revoke access tokens. By default, revocation
happens via a POST request to the path /oauth/revoke
, which expects a payload
with:
token
, the OAuth2 access token to revoke.token_type_hint => 'access_token'
, indicating that an access token is being revoked.
The payload may be delivered as application/x-www-form-urlencoded
or as JSON.
Access a test resource
When you obtain a valid token, you can access a restricted API resource. The
OAuth2 module is shipped with a test resource that is accessible with the URL
/oauth/resource
. This is a simple resource that returns JSON data.
To access the test resource, you can use the following HTTPie command:
As you can see, the OAuth2 module supports the data either via POST, using the
access_token
value, or using the Bearer
authorization header.
How to protect your API using OAuth2
You can protect your API using the following code (for instance, at the top of a controller):
where $this->server
is an instance of OAuth2\Server
(see the
AuthController.php).
All versions of api-tools-oauth2 with dependencies
bshaffer/oauth2-server-php Version ^1.14.1
rnd-cosoft/api-tools-api-problem Version ^1.5
rnd-cosoft/api-tools-content-negotiation Version ^1.8.0
laminas/laminas-crypt Version ^3.5
laminas/laminas-http Version ^2.15.1
laminas/laminas-mvc Version ^2.7.15 || ^3.3.0
laminas/laminas-mvc-i18n Version ^1.3
laminas/laminas-servicemanager Version ^3.11.1
webmozart/assert Version ^1.10