alsbury/cognito-jwt-guard

一个用于由Amazon AWS Cognito签发的JSON Web Tokens (JWT) 的laravel身份验证保护器,由benbjurstrom/cognito-jwt-guard派生而来

v0.2.0 2020-02-16 06:34 UTC

README

Amazon AWS Cognito签发的JSON Web Tokens (JWT) 的Laravel授权保护器

此项目是benbjurstrom/cognito-jwt-guard的分支,看起来已被弃用。

概述

此包提供了一个Laravel身份验证保护器,用于验证由配置的AWS Cognito用户池签发的JSON Web Tokens (JWT)。保护器接受通过Authorization头或设置为CognitoIdentityServiceProvider cookie传递的令牌。

一旦令牌通过池的公钥验证,保护器将查找一个具有cognito_uuid值等于令牌中username属性的Laravel用户。

如果找到本地Laravel用户,保护器将在请求期间对其进行身份验证。如果没有找到,并且启用了单一登录,此包将创建一个新的Laravel用户。

请注意,此包不提供用于交换用户名和密码以获取令牌的方法。因此,它打算与Laravel API驱动应用程序一起使用,其中客户端可以直接从Cognito或通过专门负责身份验证的应用程序获取令牌。

安装

您可以使用composer安装此包

composer require alsbury/cognito-jwt-guard

接下来发布迁移config/cognito.php配置文件

 php artisan vendor:publish --provider="Alsbury\CognitoGuard\CognitoServiceProvider"

接下来运行您的迁移。这将向您的用户表添加所需的cognito_uuid属性

php artisan migrate

将您的AWS Cognito用户池标识符和区域添加到.env文件

AWS_COGNITO_REGION=
AWS_COGNITO_USER_POOL_ID=

您还需要更改config/auth.php文件中的身份验证驱动程序

// config/auth.php
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'cognito', // This line is important 
        'provider' => 'users',
    ],
],

最后,根据您配置的Cognito用户池所需的属性,您可能还需要调整发布在config/cognito.php文件中的单一登录设置

// config/cognito.php
/*
|--------------------------------------------------------------------------
| Single Sign-On Settings
|--------------------------------------------------------------------------
| If sso is true the cognito guard will automatically create a new user 
| record anytime the username attribute contained in a validated JWT 
| does not already exist in the users table.
|
| The new user will be created with the user attributes listed here
| using the values stored in the given cognito user pool. Each attribute
| listed here must be set as a required attribute in your cognito user
| pool.
|
| When sso_repository_class is set this package will pass a new instance
| of the the auth provider's user model to the given class's
| createCognitoUser method. The users model will be hydrated with the given
| sso_user_attributes before it is passed.
*/

'sso'                   => env('SSO', false),
'sso_repository_class'  => null,
'sso_user_attributes'   => [
    'name',
    'email',
    ]

配置sso_repository_class是可选的,但这样做允许您在记录保存之前修改新用户记录或触发事件。一个示例sso_repository_class可能如下所示

<?php
namespace App\Repositories;

use App\Models\User;
use App\Events\UserWasRegistered;

class UserRepository
{
    public function createCognitoUser(User $user): User
    {
        $user->save();
        event(new UserWasRegistered($user));
        
        return $user;
    }
}

安全

如果您发现任何与安全相关的问题,请通过david@alsbury.com发送电子邮件,而不是使用问题跟踪器。

许可

MIT许可(MIT)。有关更多信息,请参阅许可文件