PHPackages                             devzyj/php-oauth2-server - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. devzyj/php-oauth2-server

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

devzyj/php-oauth2-server
========================

PHP OAuth2 Server

1.0.1(4y ago)0301BSD-3-ClausePHPPHP ^5.5|^7.0

Since Feb 27Pushed 4y ago1 watchersCompare

[ Source](https://github.com/devzyj/php-oauth2-server)[ Packagist](https://packagist.org/packages/devzyj/php-oauth2-server)[ RSS](/packages/devzyj-php-oauth2-server/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (2)Dependencies (3)Versions (3)Used By (1)

php-oauth2-server
=================

[](#php-oauth2-server)

PHP OAuth2 Server

Installation
============

[](#installation)

```
composer require --prefer-dist "devzyj/php-oauth2-server" "~1.0.0"
```

or add

```
"devzyj/php-oauth2-server" : "~1.0.0"
```

Usage
=====

[](#usage)

### /authorize?response\_type=xxx

[](#authorizeresponse_typexxx)

```
use devzyj\oauth2\server\AuthorizationServer;
use devzyj\oauth2\server\authorizes\CodeAuthorize;
use devzyj\oauth2\server\authorizes\ImplicitAuthorize;
use devzyj\oauth2\server\exceptions\OAuthServerException;

// 实例化授权服务器。
$authorizationServer = new AuthorizationServer([
    'accessTokenRepository' => new AccessTokenRepository(), // AccessTokenRepositoryInterface 实例。
    'authorizationCodeRepository' => new AuthorizationCodeRepository(), // AuthorizationCodeRepositoryInterface 实例。
    'clientRepository' => new ClientRepository(), // ClientRepositoryInterface 实例。
    'scopeRepository' => new ScopeRepository(), // ScopeRepositoryInterface 实例。
    'defaultScopes' => ['basic', 'basic2'], // 默认权限。
    'accessTokenDuration' => 3600, // 访问令牌持续 1 小时。
    'accessTokenCryptKey' => [
        'privateKey' => '/path/to/privateKey', // 访问令牌的私钥路径。
        'passphrase' => null, // 访问令牌的私钥密码。没有密码可以为 `null`。
        //'signKey' => 'sign key', // 字符串签名密钥。
    ],
    'authorizationCodeDuration' => 600, // 授权码持续 10 分钟。
    'authorizationCodeCryptKey' => [
        'ascii' => 'def0000086937b.....', // 使用 `vendor/bin/generate-defuse-key` 生成的字符串。
        //'path' => '/path/to/asciiFile', // 保存了 `vendor/bin/generate-defuse-key` 生成的字符串的文件路径。
        //'password' => 'string key', // 字符串密钥。
    ],
]);

// 添加授权类型。
$authorizationServer->addAuthorizeType(new CodeAuthorize());
$authorizationServer->addAuthorizeType(new ImplicitAuthorize());

try {
    // 获取并验证授权请求。
    // $request 不强制要求实现 ServerRequestInterface 接口，只需要实例中包函接口中的方法。
    $authorizeRequest = $authorizationServer->getAuthorizeRequest($request);

    // 设置授权的用户。
    // 用户未登录时，需要重定向到登录页面。
    $authorizeRequest->setUserEntity(new UserEntity()); // UserEntityInterface 实例。

    // 设置是否同意授权，同意授权设置为 `true`，拒绝授权设置为 `false`。
    // 如果用户未确认授权，需要引导用户到授权页面。
    $authorizeRequest->setIsApproved(true);

    // 运行并返回授权成功的回调地址。
    $redirectUrl = $authorizationServer->runAuthorizeTypes($authorizeRequest);
} catch (OAuthServerException $e) {
    $e->getHttpStatusCode();
    $e->getMessage();
    $e->getCode();

    // 处理异常。
    throw $e;
}

// 重定向到回调地址。
header("Location: {$redirectUrl}");
exit();
```

### /token?grant\_type=xxx

[](#tokengrant_typexxx)

```
use devzyj\oauth2\server\AuthorizationServer;
use devzyj\oauth2\server\grants\AuthorizationCodeGrant;
use devzyj\oauth2\server\grants\PasswordGrant;
use devzyj\oauth2\server\grants\ClientCredentialsGrant;
use devzyj\oauth2\server\grants\RefreshTokenGrant;
use devzyj\oauth2\server\exceptions\OAuthServerException;

// 实例化授权服务器。
$authorizationServer = new AuthorizationServer([
    'accessTokenRepository' => new AccessTokenRepository(), // AccessTokenRepositoryInterface 实例。
    'authorizationCodeRepository' => new AuthorizationCodeRepository(), // AuthorizationCodeRepositoryInterface 实例。
    'clientRepository' => new ClientRepository(), // ClientRepositoryInterface 实例。
    'refreshTokenRepository' => new RefreshTokenRepository(), // RefreshTokenRepositoryInterface 实例。
    'scopeRepository' => new ScopeRepository(), // ScopeRepositoryInterface 实例。
    'userRepository' => new UserRepository(), // UserRepositoryInterface 实例。
    'accessTokenDuration' => 3600, // 访问令牌持续 1 小时。
    'accessTokenCryptKey' => [
        'privateKey' => '/path/to/privateKey', // 访问令牌的私钥路径。
        'passphrase' => null, // 访问令牌的私钥密码。没有密码可以为 `null`。
        //'signKey' => 'sign key', // 字符串签名密钥。
    ],
    'authorizationCodeCryptKey' => [
        'ascii' => 'def0000086937b.....', // 使用 `vendor/bin/generate-defuse-key` 生成的字符串。
        //'path' => '/path/to/asciiFile', // 保存了 `vendor/bin/generate-defuse-key` 生成的字符串的文件路径。
        //'password' => 'string key', // 字符串密钥。
    ],
    'refreshTokenDuration' => 2592000, // 访问令牌持续 30 天。
    'refreshTokenCryptKey' => [
        'ascii' => 'def0000086937b.....', // 使用 `vendor/bin/generate-defuse-key` 生成的字符串。
        //'path' => '/path/to/asciiFile', // 保存了 `vendor/bin/generate-defuse-key` 生成的字符串的文件路径。
        //'password' => 'string key', // 字符串密钥。
    ],
]);

// 添加授予类型。
$authorizationServer->addGrantType(new AuthorizationCodeGrant());
$authorizationServer->addGrantType(new PasswordGrant());
$authorizationServer->addGrantType(new ClientCredentialsGrant());
$authorizationServer->addGrantType(new RefreshTokenGrant());

try {
    // 运行并返回授予的认证信息。
    // $request 不强制要求实现 ServerRequestInterface 接口，只需要实例中包函接口中的方法。
    $credentials = $authorizationServer->runGrantTypes($request);
} catch (OAuthServerException $e) {
    $e->getHttpStatusCode();
    $e->getMessage();
    $e->getCode();

    // 处理异常。
    throw $e;
}

// 显示认证信息。
echo json_encode($credentials);
```

- [Authorization Code](docs/authorization_code.md)
- [Implicit](docs/implicit.md)
- [Password](docs/password.md)
- [Client Credentials](docs/client_credentials.md)
- [Refresh Token](docs/refresh_token.md)
- [Validate Access Token](docs/validate_access_token.md)

Interfaces
==========

[](#interfaces)

需要实现的接口。

- devzyj\\oauth2\\server\\interfaces\\AccessTokenEntityInterface
- devzyj\\oauth2\\server\\interfaces\\AccessTokenRepositoryInterface
- devzyj\\oauth2\\server\\interfaces\\AuthorizationCodeEntityInterface
- devzyj\\oauth2\\server\\interfaces\\AuthorizationCodeRepositoryInterface
- devzyj\\oauth2\\server\\interfaces\\ClientEntityInterface
- devzyj\\oauth2\\server\\interfaces\\ClientRepositoryInterface
- devzyj\\oauth2\\server\\interfaces\\RefreshTokenEntityInterface
- devzyj\\oauth2\\server\\interfaces\\RefreshTokenRepositoryInterface
- devzyj\\oauth2\\server\\interfaces\\ScopeEntityInterface
- devzyj\\oauth2\\server\\interfaces\\ScopeRepositoryInterface
- devzyj\\oauth2\\server\\interfaces\\UserEntityInterface
- devzyj\\oauth2\\server\\interfaces\\UserRepositoryInterface
- devzyj\\oauth2\\server\\interfaces\\ServerRequestInterface 不强制要求实现该接口，只需要实例中包函接口中的方法。

Traits
======

[](#traits)

实现了接口中的一些方法。

- devzyj\\oauth2\\server\\traits\\AccessTokenEntityTrait
- devzyj\\oauth2\\server\\traits\\AccessTokenRepositoryTrait
- devzyj\\oauth2\\server\\traits\\AuthorizationCodeEntityTrait
- devzyj\\oauth2\\server\\traits\\AuthorizationCodeRepositoryTrait
- devzyj\\oauth2\\server\\traits\\RefreshTokenEntityTrait
- devzyj\\oauth2\\server\\traits\\RefreshTokenRepositoryTrait

Generating public and private keys
==================================

[](#generating-public-and-private-keys)

```
openssl genrsa -out private.key 2048
openssl rsa -in private.key -pubout -out public.key
```

```
openssl genrsa -passout pass:_passphrase_ -out private.key 2048
openssl rsa -in private.key -passin pass:_passphrase_ -pubout -out public.key
```

Usaging Code Challenge
======================

[](#usaging-code-challenge)

```
// 配置授权服务器。
$authorizationServer = new AuthorizationServer();
$authorizationServer->addAuthorizeType(new CodeAuthorize([
    'enableCodeChallenge' => true,
    'defaultCodeChallengeMethod' => 'S256',
]));
$authorizationServer->addGrantType(new AuthorizationCodeGrant([
    'enableCodeChallenge' => true,
]));

// 生成 Code Verifier
$codeVerifier = rtrim(strtr(base64_encode(md5(microtime())), '+/', '-_'), '='); // PHP < 7
$codeVerifier = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '='); // PHP >= 7

// 生成 Code Challenge
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
```

###  Health Score

26

—

LowBetter than 41% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~862 days

Total

2

Last Release

1810d ago

PHP version history (2 changes)1.0.0PHP &gt;=5.5.0

1.0.1PHP ^5.5|^7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/c88aa646d61c261caeccdb65d493c405562b7a4f052810a528ba8be399bec65e?d=identicon)[zhangyanjiong](/maintainers/zhangyanjiong)

---

Top Contributors

[![devzyj](https://avatars.githubusercontent.com/u/18346387?v=4)](https://github.com/devzyj "devzyj (23 commits)")

---

Tags

oauthoauth2phpserveroauthoauth2

### Embed Badge

![Health badge](/badges/devzyj-php-oauth2-server/health.svg)

```
[![Health](https://phpackages.com/badges/devzyj-php-oauth2-server/health.svg)](https://phpackages.com/packages/devzyj-php-oauth2-server)
```

###  Alternatives

[league/oauth2-server

A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.

6.7k143.0M272](/packages/league-oauth2-server)[friendsofsymfony/oauth-server-bundle

Symfony2 OAuth Server Bundle

1.1k15.3M135](/packages/friendsofsymfony-oauth-server-bundle)[patrickbussmann/oauth2-apple

Sign in with Apple OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1152.7M11](/packages/patrickbussmann-oauth2-apple)[jeremy379/laravel-openid-connect

OpenID Connect support to the PHP League's OAuth2 Server. Compatible with Laravel Passport.

59403.6k8](/packages/jeremy379-laravel-openid-connect)[simplesamlphp/simplesamlphp-module-oidc

A SimpleSAMLphp module adding support for the OpenID Connect protocol

5017.7k1](/packages/simplesamlphp-simplesamlphp-module-oidc)[chervand/yii2-oauth2-server

OAuth 2.0 server for Yii 2.0 with MAC tokens support.

1524.5k1](/packages/chervand-yii2-oauth2-server)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
