kslimani / laravel-passport-grant
Laravel Passport 自定义授权类型提供者
1.1.0
2019-10-02 12:21 UTC
Requires
- php: >=7.0
- laravel/passport: >=4.0
Requires (Dev)
- orchestra/testbench: ^4.0
- phpunit/phpunit: ^8.3
This package is not auto-updated.
Last update: 2024-09-26 12:57:01 UTC
README
laravel-passport-grant
这个库提供了一个非常简单的方式来为 Laravel Passport OAuth2 服务器添加 自定义授权类型。
安装
注意:此文档假设已完成 Laravel Passport 安装。
要开始,请通过 Composer 包管理器安装此包
composer require kslimani/laravel-passport-grant
使用 vendor:publish
Artisan 命令发布 passportgrant.php
配置文件
php artisan vendor:publish --provider="Sk\Passport\GrantTypesServiceProvider" --tag="config"
配置
在您的 config/passportgrant.php 配置文件中,启用提供用户提供者类的任何自定义授权类型。
// "grants" is an array of user provider class indexed by grant type 'grants' => [ // 'acme' => 'App\Passport\AcmeUserProvider', ],
用户提供者
用户提供者类的角色是
- 验证
/oauth/token
请求的自定义参数 - 提供用户实体实例
用户提供者类必须实现 Sk\Passport\UserProviderInterface
/** * Validate request parameters. * * @param \Psr\Http\Message\ServerRequestInterface $request * @return void * @throws \League\OAuth2\Server\Exception\OAuthServerException */ public function validate(ServerRequestInterface $request); /** * Retrieve user instance from request. * * @param \Psr\Http\Message\ServerRequestInterface $request * @return mixed|null */ public function retrieve(ServerRequestInterface $request);
如果请求验证失败,则 validate()
方法必须抛出 League\OAuth2\Server\Exception\OAuthServerException
无效参数异常。
成功时,retrieve()
方法必须返回一个 League\OAuth2\Server\Entities\UserEntityInterface
或 Illuminate\Contracts\Auth\Authenticatable
实例。否则在失败时返回 null
。
用户提供者示例
为了方便,UserProvider 类提供了验证和检索请求自定义参数的方法。
因此,创建用户提供者变得简单
<?php namespace App\Passport; use App\User; use Psr\Http\Message\ServerRequestInterface; use Sk\Passport\UserProvider; class AcmeUserProvider extends UserProvider { /** * {@inheritdoc} */ public function validate(ServerRequestInterface $request) { // It is not necessary to validate the "grant_type", "client_id", // "client_secret" and "scope" expected parameters because it is // already validated internally. $this->validateRequest($request, [ 'acme_id' => ['required', 'integer', 'min:1'], 'acme_name' => ['required', 'string', 'min:1'], ]); } /** * {@inheritdoc} */ public function retrieve(ServerRequestInterface $request) { $inputs = $this->only($request, [ 'acme_id', 'acme_name', ]); // Here insert your logic to retrieve user entity instance // For example, let's assume that users table has "acme_id" column $user = User::where('acme_id', $inputs['acme_id'])->first(); return $user; } }
令牌请求示例
请求 "acme" 授权类型的访问令牌
// Assuming $http is \GuzzleHttp\Client instance $response = $http->post('https://your-app.com/oauth/token', [ 'form_params' => [ 'grant_type' => 'acme', 'client_id' => 'client-id', 'client_secret' => 'client-secret', 'acme_id' => 1337, 'acme_name' => 'Joe', 'scope' => '', ], ]);
许可证
MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件。