Use OAuthServerPHP to implement the oau2service

Source: Internet
Author: User
Tags autoloader oauth
Currently, OAuth2.0 is widely used in network services, including third-party logon to facebook or Weibo, and logon to mobile apps. Its main purpose is as follows: if A user's photo is posted on website A, he does not need to provide website B with his username and password on website A if he wants to use the profile picture of website A on website B, while

Currently, OAuth2.0 is widely used in network services, including third-party logon to facebook or Weibo, and logon to mobile apps. Its main purpose is as follows: if A user's photo is posted on website A, he does not need to provide website B with his username and password on website A if he wants to use the profile picture of website A on website B, while

Currently, OAuth2.0 is widely used in network services, including third-party logon to facebook or Weibo, and logon to mobile apps.
Its main objectives are as follows:
If A user's photo is taken on website A and wants to use the profile picture of website A on website B, he does not need to provide website B with his username and password on website, directly give B an Access Token to get the photo of Site.
The specific process is as follows:
1) user visits website B
2) B. Verify the user's identity
3) B directs the user to website A. the user enters the account and password to log on to website.
4) website A asks if you want to grant website B the Authentication right.
5) The user tells Site A that the authentication permission can be granted to site B.
6) website A sends the Authorization Code to site B
7) Site B exchanges the Autorization Code with site A for Access Token
8) When Site B has Access Token, it has some Access permissions on Site.
This is a typical Authorization Code Grant, which is often used in network applications.

There is also the Implicit Grant authentication method, which saves the Auth Code, the open platform directly returns access_token, validity period, user ID and other data
This type of application is often used for applications without online servers, such as mobile clients or browser plug-ins.

The last one is Resource Owner Password Credentials Grant
In this case, enter the account password directly in the application, and then submit it to the open platform using XAuth technology and get the Access Token.
It is often used for PC executable programs and mobile apps. However, due to some controversy, it is difficult to develop. I will not discuss it here.

Install

You can download OAuth Server PHP on github, or use the following command to download it, but the content is the same.

?

Shell

1

2

3

mkdir my-oauth2-walkthrough

cd my-oauth2-walkthrough

git clonehttps://github.com/bshaffer/oauth2-server-php.git -b master

After that, configure the database

?

SQL

1

2

3

4

5

6

7

CREATE TABLE oauth_clients (client_id VARCHAR(80) NOT NULL, client_secret VARCHAR(80) NOT NULL, redirect_uri VARCHAR(2000) NOT NULL, grant_types VARCHAR(80), scope VARCHAR(100), user_id VARCHAR(80), CONSTRAINT clients_client_id_pk PRIMARY KEY (client_id));

CREATE TABLE oauth_access_tokens (access_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT access_token_pk PRIMARY KEY (access_token));

CREATE TABLE oauth_authorization_codes (authorization_code VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), redirect_uri VARCHAR(2000), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT auth_code_pk PRIMARY KEY (authorization_code));

CREATE TABLE oauth_refresh_tokens (refresh_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT refresh_token_pk PRIMARY KEY (refresh_token));

CREATE TABLE oauth_users (username VARCHAR(255) NOT NULL, password VARCHAR(2000), first_name VARCHAR(255), last_name VARCHAR(255), CONSTRAINT username_pk PRIMARY KEY (username));

CREATE TABLE oauth_scopes (scope TEXT, is_default BOOLEAN);

CREATE TABLE oauth_jwt (client_id VARCHAR(80) NOT NULL, subject VARCHAR(80), public_key VARCHAR(2000), CONSTRAINT jwt_client_id_pk PRIMARY KEY (client_id));

Configuration

Create a server. php file to configure the server. This file can be called by all terminals. Look at require once and you will know that this file is of the same level.

?

Server. php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

$dsn = 'mysql:dbname=my_oauth2_db;host=localhost';

$username= 'root';

$password= '';

// error reporting (this is a demo, after all!)

ini_set('display_errors',1);error_reporting(E_ALL);

// Autoloading (composer is preferred, but for this example let's just do this)

require_once('oauth2-server-php/src/OAuth2/Autoloader.php');

OAuth2\Autoloader::register();

// $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"

$storage= new OAuth2\Storage\Pdo(array('dsn'=> $dsn,'username' => $username, 'password'=> $password));

// Pass a storage object or array of storage objects to the OAuth2 server class

$server= new OAuth2\Server($storage);

// Add the "Client Credentials" grant type (it is the simplest of the grant types)

$server->addGrantType(newOAuth2\GrantType\ClientCredentials($storage));

// Add the "Authorization Code" grant type (this is where the oauth magic happens)

$server->addGrantType(newOAuth2\GrantType\AuthorizationCode($storage));

Remember to configure the user name and password for the database PDO.

Token Controller

Next, we will create a Token controller. The controller URI will return the oau2's Token to the client.

?

Token. php

1

2

3

4

5

// include our OAuth2 Server object

require_once__DIR__.'/server.php';

// Handle a request for an OAuth2.0 Access Token and send the response to the client

$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();

Test the Token controller.

Create a record to register a new application.

?

SQL

1

INSERT INTO oauth_clients (client_id, client_secret, redirect_uri) VALUES ("testclient","testpass", "http://fake/");

Then use the command line to call

?

Shell

1

curl -u testclient:testpass http://localhost/token.php -d 'grant_type=client_credentials'

The URL here is just an example. Make sure you can find the token. php
If it runs normally

?

JSON

1

{"access_token":"03807cb390319329bdf6c777d4dfae9c0d3b3c35","expires_in":3600,"token_type":"bearer","scope":null}

Resource Controller establishment and Testing

You have created a Token and you need to test it in the API, So you write the following code:

?

Resource. php

1

2

3

4

5

6

7

8

9

// include our OAuth2 Server object

require_once__DIR__.'/server.php';

// Handle a request for an OAuth2.0 Access Token and send the response to the client

if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {

$server->getResponse()->send();

die;

}

echo json_encode(array('success'=> true, 'message'=> 'You accessed my APIs!'));

Run the following command, replace YOUR_TOKEN with the token you just obtained, and ensure that the URL is correct.

?

Shell

1

curl http://localhost/resource.php -d 'access_token=YOUR_TOKEN'

If no problem occurs, the following result is displayed.

?

JSON

1

{"success":true,"message":"You accessed my APIs!"}

Create and test the authentication Controller

The verification controller is the killer of oau22. it allows your platform to help users verify third-party applications.
It does not directly return an Access Token as in the first example. It is a little more complicated here.

?

Authorize. php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

// include our OAuth2 Server object

require_once__DIR__.'/server.php';

$request = OAuth2\Request::createFromGlobals();

$response= new OAuth2\Response();

// validate the authorize request

if (!$server->validateAuthorizeRequest($request,$response)) {

$response->send();

die;

}

// display an authorization form

if (empty($_POST)) {

exit('

');

}

// print the authorization code if the user has authorized your client

$is_authorized= ($_POST['authorized'] ==='yes');

$server->handleAuthorizeRequest($request,$response, $is_authorized);

if ($is_authorized) {

// this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client

$code= substr($response->getHttpHeader('Location'),strpos($response->getHttpHeader('Location'),'code=')+5, 40);

exit("SUCCESS! Authorization Code: $code");

}

$response->send();

Then open the URL in the browser.

?

URL

1

http://localhost/authorize.php?response_type=code&client_id=testclient&state=xyz

You will see a form. When you select yes, the Authorization Code you obtained will pop up.
Now you can use this Authorization Code to obtain the token from the TOKEN. php just created. The command is as follows:

?

Shell

1

curl -u testclient:testpass http://localhost/token.php -d 'grant_type=authorization_code&code=YOUR_CODE'

Just like you did, you get a TOKEN.

?

Json

1

{"access_token":"6f05ad622a3d32a5a81aee5d73a5826adb8cbf63","expires_in":3600,"token_type":"bearer","scope":null}

Please complete this operation within 30 seconds, because the Authorization Code is only valid for 30 seconds

Use Access Token to contact a local user

After you authenticate a user and assign a Token, you may want to know which user used the Token.
You can use the optional parameter user_id of handleAuthorizeRequest to modify your authorize. php file.

?

Authorize. php

1

2

$userid = 1234; // A value on your server that identifies the user

$server->handleAuthorizeRequest($request,$response, $is_authorized, $userid);

In this way, the user ID is stored in the database along with the Token.
When the Token is used by the client, you will know which user it is. Modify resource. php to complete the task.

?

Resource. php

1

2

3

4

5

6

7

if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {

$server->getResponse()->send();

die;

}

$token = $server->getAccessTokenData(OAuth2\Request::createFromGlobals());

echo "User ID associated with this token is {$token['user_id']}";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.