Home Backend Development PHP Tutorial Analysis of the verification process using Auth2 in ThinkPHP5

Analysis of the verification process using Auth2 in ThinkPHP5

Aug 01, 2018 am 10:43 AM
php 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:
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles