Process analysis of validation using AUTH2 in ThinkPHP5

Source: Internet
Author: User
Tags dsn oauth
This article to share the content is about ThinkPHP5 in the use of Auth2 to verify the process analysis, the need for friends can refer to, hope to help everyone.

Auth2 verified on TP, found few notes on the Internet, not like yii, so write notes here to help friends with relevant needs

PS: Since Oauth2 has four kinds of scenarios, this example is based on client credential implementation, the other three kinds of will not tell

First, through the composer installation

Composer require--prefer-dist bshaffer/oauth2-server-php

After the installation is complete,

The relevant directory will appear

II. implementation of the authorization document

1) Create the corresponding data table

First find the pdo.php file,

and find the location.

The purpose is to tell you the name when creating the table, which should be the same as the table name used here

About the created table, I directly on the code, so that you can directly copy and paste:

create TABLE oauth_access_tokens (access_token varchar (+) not null,client_id varchar (+) not null,user_id int (one) DEFAULT null,expires varchar () not null,scope text, PRIMARY KEY (access_token), K EY fk_access_token_oauth2_client_client_id (client_id), KEY ix_access_token_expires (expires), CONSTRAINT Fk_access_ token_oauth2_client_client_id FOREIGN KEY (client_id) REFERENCES pos_oauth2_client (client_id) on DELETE CASCADE on Updat E CASCADE) Engine=innodb DEFAULT Charset=utf8; 
CREATE TABLE oauth_authorization_codes (authorization_code varchar () not null,client_id varchar ($) Not null,user_id Int (one) DEFAULT Null,redirect_uri text not null,expires int (one) not null,scope text,  PRIMARY KEY (Authorization_code) ,  key fk_authorization_code_oauth2_client_client_id (client_id),  key Ix_authorization_code_expires ( Expires),  CONSTRAINT fk_authorization_code_oauth2_client_client_id FOREIGN KEY (client_id) REFERENCES pos_oauth2 _client (client_id) on the DELETE CASCADE on UPDATE CASCADE) Engine=innodb DEFAULT Charset=utf8;
CREATE TABLE oauth_clients (client_id varchar) not null,client_secret varchar (no Null,redirect_uri text not null,g) Rant_type text,scope Text,created_at Int (one) default Null,updated_at int (one) default null,created_by int (one) default NULL , Updated_by Int (one) default NULL,  PRIMARY KEY (client_id)) Engine=innodb default Charset=utf8;
CREATE TABLE oauth_refresh_tokens (refresh_token varchar () not null,client_id varchar (+) not null,user_id int (one) DEFA ULT Null,expires Int (one) not null,scope text,  PRIMARY key (Refresh_token),  key Fk_refresh_token_oauth2_client_ CLIENT_ID (client_id),  KEY ix_refresh_token_expires (expires),  CONSTRAINT Fk_refresh_token_oauth2_client_ client_id FOREIGN KEY (client_id) REFERENCES pos_oauth2_client (client_id) on DELETE CASCADE on UPDATE CASCADE) Engine=inn ODB DEFAULT Charset=utf8;
CREATE TABLE oauth_scopes (Scope text,is_default tinyint (1) default NULL) Engine=myisam default Charset=utf8;

Add a piece of data

INSERT INTO  oauth_clients (Client_id,client_secret,redirect_uri,grant_type,scope,created_at,updated_at, created_by,updated_by) VALUES (' admin ', ' 123456 ', ' http://', ' client_credentials ', null,null,null,null,null);

PS, explain,

In my actual use, only the five tables are used, that is, the five tables created above, in this config, the rest of the options I have written off all the

There is another situation, explained: it is possible that you have set a table prefix for the data table, but also need to make relevant changes, such as I created, see figure:

So I made the relevant changes:

2) Create an authorization file oauth2.php, the name to take whatever you want

<?phpnamespace appcommon;/** @author jinyan@create 20180416*/use oauth2storagepdo;use thinkConfig;class Oauth2{
/** * @Register New Oauth2 Apply * @param string $action * @return boolean|\oauth2\server */function grantTypeOauth2 ($acti    On=null) {config::load (app_path. ' database.php ');            $storage = new Pdo (' dsn ' = ' + config (' DSN '), ' username ' = ' = ' config (' username '),    ' Password ' = config (' password ')]);    $server = new \oauth2\server ($storage, Array (' Enforce_state ' =>false)); Add the "Client Credentials" grant type (it is the simplest of the grant types) $server->addgranttype (New \oauth2    \granttype\clientcredentials ($storage)); Add the "Authorization Code" grant type (this is where the OAuth magic happens) $server->addgranttype (New \oauth2    \granttype\authorizationcode ($storage)); Add the "User Credentials" grant type (this is where the OAuth magic happens) $server->addgranttype (New \oauth2\g    Ranttype\usercredentials ($storage)); return $server;} /** * @ Check token value * @param unknown $server */protected function Checkapiauthroize ($server) {if (! $server->verifyresourcerequest (\oauth2\request::createfromglobals ()        ) {$server->getresponse ()->send ();    Exit }}
}?>

3) Create token file, access.php

<?phpnamespace apprestfulcontroller;use appcommonoauth2;/** @uathor: Jinyan*/class Access extends oauth2{
Protected  $_server;/** * @ Authorization configuration */public function __construct () {    return $this->_server = $this GrantTypeOauth2 ();} /** * */private function _token () {    //Handle a request for an OAuth2.0 Access token and send the response to the Clien T    $this->_server->handletokenrequest (\oauth2\request::createfromglobals ())->send (' json ', ' oauth2_ ' );} /** * @get access_token */public function Access_token () {    $this->_token ();}
}?>

So how do you ask for a Access_token value? Simply call this Acccess_token () method to

Request URL:HTTP://RESTFUL.THINKPHP.COM/R ...

Do you have to add a new data table before you create it? The role is equivalent to get Access_token account password and so on, remember the need to use POST method to obtain token

Requested parameters

{client_id=adminclient_secret=123456grant_type=client_credentials//This parameter is fixed}

If the request succeeds, it returns as shown:

Posted on the request interface via FF browser HttpRequest:

4) Get interface data through Access_token , sms.php

<?phpnamespace apprestfulcontroller;/**created by Phpstorm.user:administratordate:2018/7/29time:22:02*/use Appcommonoauth2;class Sms extends oauth2{protected $_server;/** * @ Authorization configuration */public function __construct () {    $this _server = $this->granttypeoauth2 ();} Public Function test () {    //access_token validation    $this->checkapiauthroize ($this->_server);    Echo ' successful request to data ';}}

Third, the test effect

1) first without Access_token request, test () method:

The result shows a status of 401 unverified passes

2) Then request a wrong access_token, test () method


The same is a 401 state, but at this point,

Have information back to us

3) Finally, use a correct access_token, test () method

So, based on the 1th case and the 2nd case, you should customize a method of token validation success,

End.

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.