search
HomeBackend DevelopmentPHP TutorialThe best way to implement OAuth2.0 using PHP

The best way to implement OAuth2.0 using PHP

Jun 08, 2023 am 09:09 AM
phpaccomplishoauth

OAuth2.0 is a protocol used to authorize third-party applications to access user resources. It is now widely used in the Internet field. With the development of Internet business, more and more applications need to support the OAuth2.0 protocol. This article will introduce the best way to implement the OAuth2.0 protocol using PHP.

1. Basic knowledge of OAuth2.0

Before introducing the implementation method of OAuth2.0, we need to understand some basic knowledge of OAuth2.0.

  1. Authorization type

The OAuth2.0 protocol defines 4 different authorization types: authorization code mode (authorization code), implicit authorization mode (implicit grant), Password mode (resource owner password credentials) and client mode (client credentials). Different authorization types are suitable for different scenarios. The specific authorization type to use needs to be decided based on business needs.

  1. Roles

The OAuth2.0 protocol defines three roles: resource owner, client and resource server. . The resource owner refers to the authorized user, the client refers to the third-party application, and the resource server refers to the server where the user's resources are stored.

  1. Process

The process in the OAuth2.0 protocol includes the following steps:

(1) The client requests authorization from the resource owner;

(2) The resource owner agrees to the authorization and issues an authorization code to the client;

(3) The client carries the authorization code to request an access token from the resource server;

( 4) The resource server verifies the authorization code and issues an access token to the client.

2. Implementation method

There are many mature solutions on the market for the implementation of the OAuth2.0 protocol, such as Laravel Passport, PHP League OAuth2 Server, etc. This article will focus on the implementation of PHP League OAuth2 Server.

  1. Environment setup

First, you need to create a new PHP project and install the PHP League OAuth2 Server component. The installation method is as follows:

composer require league/oauth2-server

Then, you need to create a database and create the following table structure:

``
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(4000),
user_id VARCHAR(255),
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(4000),
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(4000),
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(4000),
CONSTRAINT refresh_token_pk PRIMARY KEY (refresh_token)

);

2. 配置服务器

在PHP项目中创建一个OAuth2服务器文件,并进行基本配置。实现代码如下:

require_once DIR . '/vendor/autoload.php';

use LeagueOAuth2ServerAuthorizationServer;
use LeagueOAuth2ServerResourceServer;
use LeagueOAuth2ServerGrantClientCredentialsGrant ;
use LeagueOAuth2ServerGrantPasswordGrant;
use LeagueOAuth2ServerGrantAuthCodeGrant;
use LeagueOAuth2ServerGrantImplicitGrant;
use LeagueOAuth2ServerRepositories{AccessTokenRepositoryInterface,

AuthCodeRepositoryInterface,
ClientRepositoryInterface,
RefreshTokenRepositoryInterface,
UserRepositoryInterface};

use LeagueOAuth2Server{ResourceServer, AuthorizationValidatorsBearerTokenValidator};

/ / Configure server
$server = new AuthorizationServer(

$clientRepository,
$accessTokenRepository,
$scopeRepository,
$privateKey,
$publicKey

);

// Configure authorization type
$server->enableGrantType(new ClientCredentialsGrant());
$server->enableGrantType(

new PasswordGrant(
    $userRepository,
    $refreshTokenRepository
)

);
$server->enableGrantType(

new AuthCodeGrant(
    $authCodeRepository,
    $refreshTokenRepository,
    new DateInterval('PT10M')
)

);
$server->enableGrantType(

new ImplicitGrant(
    new DateInterval('PT1H')
)

);

//Configure the resource server
$resourceServer = new ResourceServer(

$accessTokenRepository,
$publicKey

);

//Configure the BearerTokenValidator
$bearerTokenValidator = new BearerTokenValidator(

$accessTokenRepository,
$publicKey

);

上述代码中的各个参数需要根据实际的业务需求进行具体配置。

3. 执行授权请求

在OAuth2服务器文件中,需要实现授权请求的处理逻辑。实现代码如下:

use PsrHttpMessageServerRequestInterface;
use PsrHttpMessageResponseInterface;

// Process authorization request
$server->respondToAccessTokenRequest($request , $response);

上述代码中的$request和$response分别为从HTTP传输层获取的请求参数和响应结果。需要根据实际业务需求进行具体实现。

4. 请求受保护的资源

完成授权后,客户端可以携带访问令牌请求受保护的资源。OAuth2.0服务器需要对访问令牌进行验证,并返回相应的结果。实现代码如下:

// Verify Bearer Token
try {

$bearerTokenValidator->validateAuthorization($request);

} catch (Exception $e) {

$response->getBody()->write($e->getMessage());
return $response->withHeader('Content-Type', 'text/plain')->withStatus(401);

}

// Process the access token in the request header
$accessToken = $request->getHeader('Authorization')[0];
$accessToken = substr($accessToken, strpos($accessToken, ' ' ) 1);

//Verify access token
try {

$resourceServer->validateAuthenticatedRequest($request);
$response->getBody()->write('Access granted');

} catch (Exception $e) {

$errorMessage = $e->getMessage();
$response->getBody()->write($errorMessage);
return $response->withHeader('Content-Type', 'text/plain')->withStatus(401);

}

5. 总结

The above is the detailed content of The best way to implement OAuth2.0 using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software