imrancse/passportgrant

为 Laravel Passport 定制的 grant_type

dev-master 2021-11-22 10:22 UTC

This package is auto-updated.

Last update: 2024-09-22 16:10:05 UTC


README

注意:本文档假设已完成 Laravel Passport 的安装。Laravel Passport 安装介绍

要开始,请通过 Composer 包管理器安装包

composer require imrancse/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\UserEntityInterfaceIlluminate\Contracts\Auth\Authenticatable 实例。否则在失败时返回 null

用户提供者示例

为了方便起见,UserProvider 类提供了验证和检索请求自定义参数的方法。

因此,创建用户提供者变得简单

<?php

namespace App\Passport;

use App\User;
use Psr\Http\Message\ServerRequestInterface;
use imrancse\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" grant_type 的访问令牌

// 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' => ''
            ],
]);