软体机器人/ 护照授权
为 Laravel Passport 定制的 grant_type
dev-master
2023-01-06 08:43 UTC
Requires
This package is not auto-updated.
Last update: 2024-09-28 02:14:47 UTC
README
注意:此文档假设已完成 Laravel Passport 安装。
要开始,请使用 Composer 包管理器安装包
composer require softrobotics/passportgrant
使用 vendor:publish Artisan 命令发布 passport_grant_type.php 配置文件
php artisan vendor:publish --provider="imrancse\passportgrant\PassportGrantServiceProvider" --tag="config"
配置
在您的 config/passport_grant_type.php 配置文件中,启用任何自定义 grant_type 并提供用户提供者类。
// "grants" is an array of user provider class indexed by grant type
'grants' => [
// 'otp_grant' => 'App\Passport\OTPGrantProvider',
],
用户提供者
用户提供者类的角色是
- 验证
/oauth/token请求的自定义参数 - 提供用户实体实例
用户提供者类必须实现 imrancse\passportgrant\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 softrobotics\passportgrant\UserProvider;
class OTPGrantProvider 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, [
'email' => ['required', 'email'],
]);
}
/**
* {@inheritdoc}
*/
public function retrieve(ServerRequestInterface $request)
{
$inputs = $this->only($request, [
'email'
]);
// Here insert your logic to retrieve user entity instance
// For example, let's assume that users table has "email" column
$user = User::where('email', $inputs['email'])->first();
return $user;
}
}
令牌请求示例
请求 "otp_grant" 授权类型的访问令牌
// You have to import "Illuminate\Support\Facades\Http"
$response = Http::asForm()->post('https://your-app.com/oauth/token', [
'grant_type' => 'otp_grant',
'client_id' => <client-id>,
'client_secret' => <client-secret>,
'email'=>'<user-email>',
'scope' => ''
],
]);