Analysis of the verification process using Auth2 in ThinkPHP5

不言
Release: 2023-04-03 13:58:02
Original
4596 people have browsed it

The content of this article is to share with you the analysis of the verification process using Auth2 in ThinkPHP5. Friends in need can refer to it. I hope it can help everyone.

Regarding the auth2 verification implemented on tp, I found very few notes on the Internet, unlike yii, so I will post some notes here to help friends with related needs

PS: In view of There are four solutions for oauth2. This example is based on client credentials. The other three will not be described.

1. Installation through composer

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

After the installation is completed, as shown in the figure:
Analysis of the verification process using Auth2 in ThinkPHP5
The relevant directory will appear

2. Implement the authorization file

1) Create the corresponding data table

First find the Pdo.php file, as shown in the figure:

Analysis of the verification process using Auth2 in ThinkPHP5

Then find the location

Analysis of the verification process using Auth2 in ThinkPHP5

Purpose, is to tell you the name when creating the table, it should be the same as The table names used here are the same

Regarding the created table, I directly upload the code so that you can copy and paste directly:

CREATE TABLE 
oauth_access_tokens
 (
access_token
 varchar(40) NOT NULL,
client_id
 varchar(80) NOT NULL,
user_id
 int(11) DEFAULT NULL,
expires
 varchar(19) NOT NULL,
scope
 text,
  PRIMARY KEY (
access_token
),
  KEY 
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 UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login
CREATE TABLE 
oauth_authorization_codes
 (
authorization_code
 varchar(40) NOT NULL,
client_id
 varchar(80) NOT NULL,
user_id
 int(11) DEFAULT NULL,
redirect_uri
 text NOT NULL,
expires
 int(11) 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 DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login
CREATE TABLE 
oauth_clients
 (
client_id
 varchar(80) NOT NULL,
client_secret
 varchar(80) NOT NULL,
redirect_uri
 text NOT NULL,
grant_type
 text,
scope
 text,
created_at
 int(11) DEFAULT NULL,
updated_at
 int(11) DEFAULT NULL,
created_by
 int(11) DEFAULT NULL,
updated_by
 int(11) DEFAULT NULL,
  PRIMARY KEY (
client_id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login
CREATE TABLE 
oauth_refresh_tokens
 (
refresh_token
 varchar(40) NOT NULL,
client_id
 varchar(80) NOT NULL,
user_id
 int(11) DEFAULT NULL,
expires
 int(11) 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=InnoDB DEFAULT CHARSET=utf8;
Copy after login
CREATE TABLE 
oauth_scopes
 (
scope
 text,
is_default
 tinyint(1) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Copy after login

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);
Copy after login

PS, please explain, as shown in the picture:

Analysis of the verification process using Auth2 in ThinkPHP5

In my actual use, I only use these five tables, that is For the five tables created above, in this config, I have logged out all the remaining options

There is another situation that I would like to explain: Maybe everyone, The table prefix is ​​set for the data table, and relevant modifications need to be made here. For example, I created it, see the picture:

Analysis of the verification process using Auth2 in ThinkPHP5

So I made relevant modifications:

Analysis of the verification process using Auth2 in ThinkPHP5

2) Create the authorization file Oauth2.php, and name it whatever you want

<?phpnamespace appcommon;/**
@author jinyan
@create 20180416
*/use OAuth2StoragePdo;use thinkConfig;
class Oauth2{
Copy after login
/**
 * @Register new Oauth2 apply
 * @param string $action
 * @return boolean|\OAuth2\Server
 */
function grantTypeOauth2($action=null)
{
    Config::load(APP_PATH.&#39;database.php&#39;);

    $storage = new Pdo(
        [
            &#39;dsn&#39;      => config(&#39;dsn&#39;),
            &#39;username&#39; => config(&#39;username&#39;),
            &#39;password&#39; => config(&#39;password&#39;)
        ]
    );

    $server = new \OAuth2\Server($storage, array(&#39;enforce_state&#39;=>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\GrantType\UserCredentials($storage));
    return $server;
}

/**
 * @校验token值
 * @param unknown $server
 */
protected function checkApiAuthroize($server)
{
    if (!$server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
        $server->getResponse()->send();
        exit;
    }
}
Copy after login
}
?>
Copy after login
Copy after login

3) Create the token file, Access.php

<?phpnamespace apprestfulcontroller;use appcommonOauth2;
/**
@uathor:jinyan
*/
class Access extends Oauth2{
Copy after login
protected  $_server;

/**
 * @授权配置
 */
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 client
    $this->_server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send(&#39;json&#39;, &#39;oauth2_&#39;);
}

/**
 * @get access_token
 */
public function access_token()
{
    $this->_token();
}
Copy after login
}
?>
Copy after login
Copy after login

So how to request an access_token value? Just call the access_token() method directly

request url: http://restful.thinkphp.com/r...

Please also add something when creating the data table before Got a new piece of data? Its function is equivalent to obtaining the account password of access_token. Remember to use the Post method to obtain the token

Parameters of the request

{
client_id=admin
client_secret=123456
grant_type=client_credentials //这个参数是固定的
}
Copy after login

If the request is successful, the following will be returned As shown in the picture:

Analysis of the verification process using Auth2 in ThinkPHP5

Paste, through the request interface of ff browser httprequest:

Analysis of the verification process using Auth2 in ThinkPHP5

4) Obtain interface data through access_token,Sms.php

<?php
namespace apprestfulcontroller;
/**
Created by PhpStorm.
User: Administrator
Date: 2018/7/29
Time: 22:02
*/
use appcommonOauth2;
class Sms extends Oauth2
{
protected $_server;

/**
 * @授权配置
 */
public function __construct()
{
    $this->_server = $this->grantTypeOauth2();
}

public function test()
{
    //access_token验证
    $this->checkApiAuthroize($this->_server);

    echo &#39;成功请求到数据&#39;;
}
}
Copy after login

3. The test effect is as shown in the figure:

1) First, without access_token request, test() method:

Analysis of the verification process using Auth2 in ThinkPHP5

The result is a 401 unverified status

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

Analysis of the verification process using Auth2 in ThinkPHP5
is also a 401 status, but at this time, as shown in the figure

Analysis of the verification process using Auth2 in ThinkPHP5

There is information returned to us

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

Analysis of the verification process using Auth2 in ThinkPHP5

So, based on the first and second situations, you should customize a method for failure of token verification, as shown in the figure:

Analysis of the verification process using Auth2 in ThinkPHP5

Analysis of the verification process using Auth2 in ThinkPHP5

Analysis of the verification process using Auth2 in ThinkPHP5

Analysis of the verification process using Auth2 in ThinkPHP5

# end.

Recommended related articles:

php implementation for verifying all types of credit card classes

thinkphp verification code implementation ( form, ajax implementation verification)_php example

The above is the detailed content of Analysis of the verification process using Auth2 in ThinkPHP5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template