Analysis of the verification process using Auth2 in ThinkPHP5
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:
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:
Then find the location
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;
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;
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;
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;
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, please explain, as shown in the picture:
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:
So I made relevant modifications:
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{
/** * @Register new Oauth2 apply * @param string $action * @return boolean|\OAuth2\Server */ function grantTypeOauth2($action=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\GrantType\UserCredentials($storage)); return $server; } /** * @校验token值 * @param unknown $server */ protected function checkApiAuthroize($server) { if (!$server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) { $server->getResponse()->send(); exit; } }
} ?>
3) Create the token file, Access.php
<?phpnamespace apprestfulcontroller;use appcommonOauth2; /** @uathor:jinyan */ class Access extends Oauth2{
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('json', 'oauth2_'); } /** * @get access_token */ public function access_token() { $this->_token(); }
} ?>
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 //这个参数是固定的 }
If the request is successful, the following will be returned As shown in the picture:
Paste, through the request interface of ff browser httprequest:
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 '成功请求到数据'; } }
3. The test effect is as shown in the figure:
1) First, without access_token request, test() method:
The result is a 401 unverified status
2) Then request a wrong access_token, the test() method
is also a 401 status, but at this time, as shown in the figure
There is information returned to us
3) Finally, use a correct access_token, test() method
So, based on the first and second situations, you should customize a method for failure of token verification, as shown in the figure:
# 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
