ybelenko/oauth2_email_grant

符合league/oauth2-server包的OAuth2 Email Grant自定义包。

1.0.0 2022-11-22 16:46 UTC

This package is auto-updated.

Last update: 2024-09-23 03:48:25 UTC


README

Tests Coverage Status

要求

  • PHP 8.x

重要通知

如果您决定扩展一些类,请确保不要在某个地方暴露访问令牌。检查您没有使用echo/print/var_dump输出访问令牌或其实例。

通过Composer进行安装

在命令行中运行

composer require ybelenko/oauth2_email_grant

基本用法

假设您已经安装并配置了PHP League OAuth 2.0 Server

use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\UserEntityInterface;
use Ybelenko\OAuth2\Server\Grant\CustomEmailGrant;

// if you want to use class method instead of anonymous functions
// do $onAccessToken = \Closure::fromCallable([$this, 'onAccessToken'])
// or when method is static $onAccessToken = \Closure::fromCallable([UserClass::class, 'onAccessToken'])

$grant = new CustomEmailGrant(
    $userRepository, // repository used in your oauth2 server implementation
    static function (
        string $email,
        AccessTokenEntityInterface $accessToken,
        ClientEntityInterface $client, 
        UserEntityInterface $user,
        array $scopes
    ) {
        // send access token to user via email
        // or do something else
    },
    static function (string $email) {
        // validate email the way you want
        // throw an exception or return true|false
        // everything beside true return will stop token creation
    }
);

// all other repos should be added from auth server automatically
// right after you call
$server->enableGrantType($grant, new \DateInterval('PT1H'));

然后在您的UserRepositoryInterface实现中处理新的自定义授权

/**
 * {@inheritdoc}
 */
public function getUserEntityByUserCredentials(
    $username,
    $password,
    $grantType,
    ClientEntityInterface $clientEntity
) {
    if ($grantType === 'custom_email') {
        // password is empty string now
        // just for readability
        $email = $username;
        // if user with provided email exists return new entity
        // otherwise return null
        // don't need to check password since we send token
        // to provided email, works like common account recover flow
        $user = new FakeUserEntity();
        $user->setIdentifier($email);
        return $user;
    }

    // handle other grants also check password from now

    return null;
}

要使用新的授权,用户可以发送POST请求,只需稍作修改(将grant_type更改为custom_email,新增字段email

{
    "grant_type": "custom_email",
    "client_id": "client",
    "client_secret": "secret",
    "email": "johndoe@example.dev",
    "scope": "foo baz bar"
}

也可以通过HTTP头部发送client_idclient_secret,格式为"Authorization: Basic {base64_encode($clientId . ':' . $clientSecret)}"

用户收到的响应将是类似以下的内容

{
    "message": "Mail with recover link has been sent to provided address",
    "expires_in": 3600
}

作者

Yuriy Belenko