xutl / laravel-passport-sms

这是一个用于 SMS 的 Laravel passport 授权。

1.0.0 2018-10-11 02:21 UTC

This package is auto-updated.

Last update: 2024-09-11 15:36:02 UTC


README

此包非常有用,可以将您的 Oauth2 服务器与 SMS 登录结合使用。

安装

此包可以通过 Composer 安装。

composer require xutl/laravel-passport-sms

在 Laravel 5.5 中,服务提供者将自动注册。在框架的旧版本中,只需将服务提供者添加到 config/app.php 文件中即可。

// config/app.php
'providers' => [
    ...
    "XuTL\Passport\Sms\SmsLoginGrantProvider::class,
    ...
];

使用方法

  • https://your-site.com/oauth/token 发送 POST 请求,就像使用密码或刷新授权一样。
  • POST 主体应包含 grant_type = sms。
  • 请求将被路由到您的 User::byPassportSmsRequest() 函数,在那里您将确定是否授予访问权限。
  • 如果成功,将返回 access_token 和 refresh_token。

请求

$response = $http->post('http://your-app.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'sms',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'phone' => '13800138000', 
        'verifyCode' => 'SMS verifyCode',
    ],
]);

## Example

Here is what a `User::byPassportSmsRequest()` method might look like...

```php
/**
 * Verify and retrieve user by custom token request.
 *
 * @param \Illuminate\Http\Request $request
 *
 * @return \Illuminate\Database\Eloquent\Model|null
 * @throws \League\OAuth2\Server\Exception\OAuthServerException
 */
public function byPassportSmsequest(Request $request)
{
    try {
                Validator::make($request->all(), [
                    'phone' => [
                        'required',
                        'min:11',
                        'max:11',
                        'regex:/^1[34578]{1}[\d]{9}$|^166[\d]{8}$|^19[89]{1}[\d]{8}$/',
                    ],
                    'verifyCode' => [
                        'required',
                        'max:6',
                        function ($attribute, $value, $fail) use ($request) {
                            if (!SmsVerifyCodeService::make($request->phone)->validate($value, false)) {
                                return $fail($attribute . ' is invalid.');
                            }
                        },
                    ]
                ])->validate();
                return static::phone($request->phone)->first();
            } catch (\Exception $e) {
                throw OAuthServerException::accessDenied($e->getMessage());
            }
}

在此示例中,该应用程序能够根据提交的 JSON 有效载荷中的 phone 和 `verifyCode 属性验证用户。它将返回 null 或用户对象。它还可能抛出异常,解释令牌无效的原因。`byPassportSmsRequest` 捕获这些异常并将它们转换为适当的 OAuth 异常类型。如果请求有效载荷中没有 `phone`,则我们返回 `null`,这返回一个 invalid_credentials 错误响应。

{
  "error": "invalid_credentials",
  "message": "The user credentials were incorrect."
}

致谢