{"id":15027076,"url":"https://github.com/ellaisys/aws-cognito","last_synced_at":"2025-05-15T16:05:37.994Z","repository":{"id":40964160,"uuid":"291793440","full_name":"ellaisys/aws-cognito","owner":"ellaisys","description":"AWS Cognito package (with MFA Feature) using the AWS SDK for PHP/Laravel","archived":false,"fork":false,"pushed_at":"2025-02-01T11:06:26.000Z","size":796,"stargazers_count":116,"open_issues_count":12,"forks_count":51,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-05-07T19:59:12.661Z","etag":null,"topics":["api-authentication","authentication","authentication-middleware","aws","aws-cognito","aws-sdk","cognito","cognito-pool","google-authenticator","jwt","laravel","laravel-api-auth","laravel-cognito","laravel-package","mfa","php","php8","user-pool"],"latest_commit_sha":null,"homepage":"https://ellaisys.github.io/aws-cognito/","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ellaisys.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-08-31T18:27:10.000Z","updated_at":"2025-05-07T10:27:37.000Z","dependencies_parsed_at":"2023-02-09T04:17:44.449Z","dependency_job_id":"aee957d5-bee0-4300-a662-b6634c0f5cca","html_url":"https://github.com/ellaisys/aws-cognito","commit_stats":{"total_commits":218,"total_committers":16,"mean_commits":13.625,"dds":0.5963302752293578,"last_synced_commit":"bd69e747af29fb042db83d0308f0cb4fe2f59dd3"},"previous_names":[],"tags_count":40,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ellaisys%2Faws-cognito","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ellaisys%2Faws-cognito/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ellaisys%2Faws-cognito/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ellaisys%2Faws-cognito/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ellaisys","download_url":"https://codeload.github.com/ellaisys/aws-cognito/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254374427,"owners_count":22060611,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-authentication","authentication","authentication-middleware","aws","aws-cognito","aws-sdk","cognito","cognito-pool","google-authenticator","jwt","laravel","laravel-api-auth","laravel-cognito","laravel-package","mfa","php","php8","user-pool"],"created_at":"2024-09-24T20:05:44.219Z","updated_at":"2025-05-15T16:05:37.934Z","avatar_url":"https://github.com/ellaisys.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cimg src=\"./assets/images/banner.png\" width=\"100%\" alt=\"Laravel AWS Cognito Package for Web and API authentication with MFA Feature\"/\u003e\n\n# Laravel AWS Cognito Package for Web and API authentication with MFA Feature\nAWS Cognito package using the AWS SDK for PHP\n\n[![Release Version](https://img.shields.io/packagist/v/ellaisys/aws-cognito?style=flat-square\u0026logo=packagist\u0026logoColor=whitesmoke\u0026label=Release\u0026nbsp;Version)](https://packagist.org/packages/ellaisys/aws-cognito#v1.1.3)\u0026#160;\n[![Release Date](https://img.shields.io/github/release-date/ellaisys/aws-cognito?style=flat-square\u0026logo=packagist\u0026logoColor=whitesmoke\u0026label=Release\u0026nbsp;Date)](https://packagist.org/packages/ellaisys/aws-cognito)\u0026#160;\n[![Total Downloads](https://img.shields.io/packagist/dt/ellaisys/aws-cognito?style=flat-square\u0026logo=packagist\u0026logoColor=whitesmoke\u0026label=Downloads)](https://packagist.org/packages/ellaisys/aws-cognito)\u0026#160;\n\n![Github Stars](https://img.shields.io/github/stars/ellaisys/aws-cognito?style=flat-square\u0026logo=github\u0026logoColor=whitesmoke\u0026label=Stars)\u0026#160;\n![Github Forks](https://img.shields.io/github/forks/ellaisys/aws-cognito?style=flat-square\u0026logo=github\u0026logoColor=whitesmoke\u0026label=Forks)\u0026#160;\n[![GitHub Contributors](https://img.shields.io/github/contributors-anon/ellaisys/aws-cognito?style=flat\u0026logo=github\u0026logoColor=whitesmoke\u0026label=Contributors)](CONTRIBUTING.md)\u0026#160;\n[![APM](https://img.shields.io/packagist/l/ellaisys/aws-cognito?style=flat-square\u0026logo=github\u0026logoColor=whitesmoke\u0026label=License)](LICENSE.md)\n\n[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=ellaisys_aws-cognito\u0026metric=alert_status)](https://sonarcloud.io/summary/new_code?id=ellaisys_aws-cognito)\n[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=ellaisys_aws-cognito\u0026metric=security_rating)](https://sonarcloud.io/summary/new_code?id=ellaisys_aws-cognito)\n[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=ellaisys_aws-cognito\u0026metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=ellaisys_aws-cognito)\n\n\nThis package provides a simple way to use AWS Cognito authentication in Laravel for Web and API Auth Drivers.\nThe idea of this package, and some of the code, is based on the package from Pod-Point which you can find here: [Pod-Point/laravel-cognito-auth](https://github.com/Pod-Point/laravel-cognito-auth), [black-bits/laravel-cognito-auth](https://github.com/black-bits/laravel-cognito-auth) and [tymondesigns/jwt-auth](https://github.com/tymondesigns/jwt-auth).\n\n**[DEMO Application](https://demo.ellaisys.com/cognito)**. You can try and register and login. For the first time, it will force the user to change password. The **[source code](https://github.com/ellaisys/demo_cognito_app)** of the demo application is also available of the GitHub.\n\nWe decided to use it and contribute it to the community as a package, that encourages standarised use and a RAD tool for authentication using AWS Cognito.\n\n## Features\n- [Registration and Confirmation E-Mail (Sign Up)](#registering-users)\n- Forced password change at first login (configurable)\n- [Login (Sign In)](#user-authentication)\n- Token Validation for all Session and Token Guard Requests\n- Remember Me Cookie\n- Single Sign On **Updated** (Fix: Issue #86)\n- Forgot Password (Resend - configurable)\n- User Deletion\n- Edit User Attributes\n- Reset User Password\n- Confirm Sign Up\n- Easy API Token handling (uses the cache driver)\n- [DynamoDB support for Web Sessions and API Tokens (useful for server redundency OR multiple containers)](#storing-web-sessions-or-api-tokens-in-dynamodb-useful-for-multiservercontainer-implementation)\n- Easy configuration of Token Expiry (Manage using the cognito console, no code or configurations needed)\n- Support for App Client without Secret\n- Support for Cognito Groups, including assigning a default group to a new user\n- Session (Web) now has AccessToken and RefreshToken as part of the claim object\n- [Logout (Sign Out) - Remove access tokens from AWS](#signout-remove-access-token)\n- [Forced Logout (Sign Out) - Revoke the RefreshToken from AWS](#signout-remove-access-token)\n- [MFA Implementation for Session and Token Guards](./README_MFA.md)\n- [Password validation based on Cognito Configuration](#password-validation-based-of-cognito-configuration)\n- [Mapping Cognito User using Subject UUID](#mapping-cognito-user-using-subject-uuid) **NEW**\n\n## Compatability\n\n|PHP Version|Support|\n|-|-|\n|7.4|Yes :heavy_check_mark:|\n|8.0|Yes :heavy_check_mark:|\n|8.1|Yes :heavy_check_mark:|\n|8.24|Yes :heavy_check_mark:|\n\n|Laravel Version|Support|\n|-|-|\n|7.x|Yes :heavy_check_mark:|\n|8.x|Yes :heavy_check_mark:|\n|9.x|Yes :heavy_check_mark:|\n|10.x|Not tested|\n\n## Installation\n\nYou can install the package via composer.\n\n```bash\ncomposer require ellaisys/aws-cognito\n```\n\n### Laravel 5.4 and before\nUsing a version prior to Laravel 5.5 you need to manually register the service provider.\n\n```php\n    // config/app.php\n    'providers' =\u003e [\n        ...\n        Ellaisys\\Cognito\\Providers\\AwsCognitoServiceProvider::class,\n        \n    ];\n```\n\n### Configuration File: Next you can publish the config.\n\n```bash\n    php artisan vendor:publish --provider=\"Ellaisys\\Cognito\\Providers\\AwsCognitoServiceProvider\"\n```\nLast but not least you want to change the auth driver. To do so got to your config\\auth.php file and change it\nto look the following:\n\n```php\n    'guards' =\u003e [\n        'web' =\u003e [\n            'driver' =\u003e 'cognito-session', // This line is important for using AWS Cognito as Web Driver\n            'provider' =\u003e 'users',\n        ],\n        'api' =\u003e [\n            'driver' =\u003e 'cognito-token', // This line is important for using AWS Cognito as API Driver\n            'provider' =\u003e 'users',\n        ],\n    ],\n```\n\u003e[!IMPORTANT]\n\u003eThis is a new feature that is released in V1.2.0 and shall work with Laravel 8.37 (with anonymous migration support). For verions below Laravel 8.37, this feature is disabled. You will need to update the **users** table migration and add the **sub** column (type:string, nullable:yes, index:yes).\n\n### Database Migrations\nThe AWS Cognito service provider registers its own database migration directory, so remember to migrate your database after installing the package. The AWS Cognito migrations will add a few columns to your **users** table:\n\n```bash\n    php artisan migrate\n```\n\nIf you need to overwrite the migrations that ship with AWS Cognito, you can publish them using the vendor:publish Artisan command:\n\n```bash\n    php artisan vendor:publish --tag=\"cognito-migrations\"\n```\n\nIf you would like to prevent AWS Cognito's migrations from running entirely, you may use the ignoreMigrations method provided by AWS Cognito. Typically, this method should be called in the register method of your AppServiceProvider:\n```php\n    use Ellaisys\\Cognito\\AwsCognito;\n    \n    /**\n     * Register any application services.\n     */\n    public function register(): void\n    {\n        AwsCognito::ignoreMigrations();\n    }\n```\n\n\n## Cognito User Pool\n\nIn order to use AWS Cognito as authentication provider, you require a Cognito User Pool.\n\nIf you haven't created one already, go to your [Amazon management console](https://console.aws.amazon.com/cognito/home) and create a new user pool.\n\nNext, generate an App Client. This will give you the App client id and the App client secret\nyou need for your `.env` file.\n\n*IMPORTANT: Don't forget to activate the checkbox to Enable sign-in API for server-based Authentication.\nThe Auth Flow is called: ADMIN_USER_PASSWORD_AUTH (formerly ADMIN_NO_SRP_AUTH)*\n\n### AWS IAM configuration\n\nYou also need a new **IAM Role** with the following Access Rights:\n\n- AmazonCognitoDeveloperAuthenticatedIdentities\n- AmazonCognitoPowerUser\n- AmazonESCognitoAccess\n\nFrom this IAM User you must use the **AWS_ACCESS_KEY_ID** and **AWS_SECRET_ACCESS_KEY** in the laravel environment file.\n\n### Cognito configuration\n\nAdd the following fields to your `.env` file and set the values according to your AWS settings:\n\n```php\n    # AWS configurations for cloud storage\n    AWS_ACCESS_KEY_ID=\"Axxxxxxxxxxxxxxxxxxxxxxxx6\"\n    AWS_SECRET_ACCESS_KEY=\"mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+\"\n\n    # AWS Cognito configurations\n    AWS_COGNITO_CLIENT_ID=\"6xxxxxxxxxxxxxxxxxxxxxxxxr\"\n    AWS_COGNITO_CLIENT_SECRET=\"1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1\"\n    AWS_COGNITO_USER_POOL_ID=\"xxxxxxxxxxxxxxxxx\"\n    AWS_COGNITO_REGION=\"xxxxxxxxxxx\" //optional - default value is 'us-east-1'\n    AWS_COGNITO_VERSION=\"latest\" //optional - default value is 'latest'\n\n```\n\u003e[!IMPORTANT]\n\u003eTo sync the web session timeout with the cognito access token ttl value, set the **SESSION_LIFETIME** parameter in the .env file. This value is in minutes with the default value being 120 mins i.e. 2 hours. This will ensure that the laravel session times out at the same time as the access token.\n\nFor more details on how to find AWS_COGNITO_CLIENT_ID, AWS_COGNITO_CLIENT_SECRET and AWS_COGNITO_USER_POOL_ID for your application, please refer [COGNITOCONFIG File](COGNITOCONFIG.md)\n\n### Importing existing users into the Cognito Pool\n\nIf you are already working on an existing project and want to integrate Cognito you have to [import a user csv file to your Cognito Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html).\n\n## Usage\nOur package is providing you 6 traits you can just add to your Auth Controllers to get our package running.\n\n- Ellaisys\\Cognito\\Auth\\AuthenticatesUsers\n- Ellaisys\\Cognito\\Auth\\RegistersUsers\n- Ellaisys\\Cognito\\Auth\\ResetsPasswords\n- Ellaisys\\Cognito\\Auth\\RespondsMFAChallenge\n- Ellaisys\\Cognito\\Auth\\SendsPasswordResetEmails\n- Ellaisys\\Cognito\\Auth\\VerifiesEmails\n\n\nIn the simplest way you just go through your Auth Controllers and change namespaces from the traits which are currently implemented from Laravel.\n\nYou can change structure to suit your needs. Please be aware of the @extend statement in the blade file to fit into your project structure.\nAt the current state you need to have those 4 form fields defined in here. Those are `token`, `email`, `password`, `password_confirmation`.\n\n## Single Sign-On\n\nWith our package and AWS Cognito we provide you a simple way to use Single Sign-Ons.\nFor configuration options take a look at the config [cognito.php](/config/cognito.php).\n\nWhen you want SSO enabled and a user tries to login into your application, the package checks if the user exists in your AWS Cognito pool. If the user exists, he will be created automatically in your database provided the `add_missing_local_user` is to `true`, and is logged in simultaneously.\n\nThat's what we use the fields `sso_user_model` and `cognito_user_fields` for. In `sso_user_model` you define the class of your user model. In most cases this will simply be _App\\Models\\User_.\n\nWith `cognito_user_fields` you can define the fields which should be stored in Cognito. Put attention here. If you define a field which you do not send with the Register Request this will throw you an InvalidUserFieldException and you won't be able to register.\n\nNow that you have registered your users with their attributes in the AWS Cognito pool and your database and you want to attach a second app which should use the same pool. Well, that's actually pretty easy. You can use the API provisions that allows multiple projects to consume the same AWS Cognito pool.\n\n*IMPORTANT: if your users table has a password field you are not going to need this anymore. What you want to do is set this field to be nullable, so that users can be created without passwords. From now on, Passwords are stored in Cognito.\n\nAny additional registration data you have, for example `firstname`, `lastname` needs to be added in\n[cognito.php](/config/cognito.php) cognito_user_fields config to be pushed to Cognito. Otherwise they are only stored locally\nand are not available if you want to use Single Sign On's.*\n\n## Forgot password with resend option\n\nIn case the user has not activated the account, AWS Cognito as a default feature does not allow user of use the forgot password feature. We have introduced the AWS documented feature that allows the password to be resent.\n\nWe have made this configurable for the developers so that they can use it as per the business requirement. The configuration takes a boolean value. Default is true (allows resend of forgot password)\n\n```php\n\n    AWS_COGNITO_ALLOW_FORGOT_PASSWORD_RESEND=true\n\n```\n\n## Middleware configuration for API Routes\nIn case you are using this library as API driver, you can register the middleware into the kernal.php in the $routeMiddleware\n\n```php\n\n    protected $routeMiddleware = [\n        ...\n        'aws-cognito' =\u003e \\Ellaisys\\Cognito\\Http\\Middleware\\AwsCognitoAuthenticate::class\n    ]\n\n```\n\nTo use the middleware into the **Web routes**, you can use the std auth middleware as shown below\n\n```php\n\n    Route::middleware('auth')-\u003eget('user', 'NameOfTheController@functionName');\n\n```\n\nTo use the middleware into the **API routes**, as shown below\n\n```php\n\n    Route::middleware('aws-cognito')-\u003eget('user', 'NameOfTheController@functionName');\n\n```\n\n\n## Registering Users\n\nAs a default, if you are registering a new user with Cognito, Cognito will send you an email during signUp that includes the username and temporary password for the users to verify themselves.\n\nUsing this library in conjunction with **AWS Lambda**, once can look to customize the email template and content. The email template can be text or html based. The Lambda code for not included in this code repository. You can create your own. Any object (array) that you pass to the registration method is transferred as is to the lambda function, we are not prescriptive about the attribute names.\n\nWe have made is very easy for anyone to use the default behaviour.\n\n1. You don't need to create an extra field to store the verification token.\n2. You don't have to bother about the Sessions or API tokens, they are managed for you. The session or token is managed via the standard mechanism of Laravel. You have the liberty to keep it where ever you want, no security loop holes.\n3. If you use the trait provided by us 'Ellaisys\\Cognito\\Auth\\RegistersUsers', the code will be limited to just a few lines\n4. if you are using the Laravel scafolding, then make the password nullable in DB or drop it from schema. Passwords will be only managed by AWS Cognito.\n\n```php\n    use Ellaisys\\Cognito\\Auth\\RegistersUsers;\n\n    class UserController extends BaseController\n    {\n        use RegistersUsers;\n\n        public function register(Request $request)\n        {\n            $validator = $request-\u003evalidate([\n                'name' =\u003e 'required|max:255',\n                'email' =\u003e 'required|email|max:64|unique:users',\n                'password' =\u003e 'sometimes|confirmed|min:6|max:64',\n            ]);\n\n            //Create credentials object\n            $collection = collect($request-\u003eall());\n            $data = $collection-\u003eonly('name', 'email', 'password'); //passing 'password' is optional.\n\n            //Register User in cognito\n            if ($cognitoRegistered=$this-\u003ecreateCognitoUser($data)) {\n\n                //If successful, create the user in local db\n                User::create($collection-\u003eonly('name', 'email'));\n            } //End if\n\n            //Redirect to view\n            return view('login');\n        }\n    }\n\n```\n\n5. You don't need to turn off Cognito to send you emails. We rather propose the use of AWS Cognito or AWS SMS mailers, such that user credentials are always secure.\n\n6. In case you want to suppress the mails to be sent to the new users, you can configure the parameter given below to skip welcome mails to new user registration. Default configuration shall send the welcome email.\n\n```php\n\n    AWS_COGNITO_NEW_USER_MESSAGE_ACTION=\"SUPPRESS\"\n\n```\n\n7. The configuration given below allows the new user's email address to be auto marked as verified.\n\n```php\n\n    AWS_COGNITO_FORCE_NEW_USER_EMAIL_VERIFIED=true //optional - default value is false.\n\n```\n\n8. To assign a default group to a new user when registering set a name of the user group as per the configuration done via AWS Cognito Management Console. The default value is set to null.\n\n```php\n\n    AWS_COGNITO_DEFAULT_USER_GROUP=\"Customers\"\n\n```\n\n9. To enable custom password or user defined password, the below configuration if set to **true** will force the user to set the password during registration, else cognito will generate a random password and send over email and/or SMS based on the configurations.\n\n```php\n\n    AWS_COGNITO_FORCE_NEW_USER_PASSWORD=true //optional - default value is false.  \n\n```\n\n## User Authentication\n\nWe have provided you with a useful trait that make the authentication very simple (with Web or API routes). You don't have to worry about any additional code to manage sessions and token (for API).\n\n\u003e [!NOTE]\n\u003e The Access Token is now validated with the AWS Cognito certificate. If the certificate is incorrect or expired, it will throw am exception.\n\nThe trait takes in some additional parameters, refer below the function signature of the trait. Note that the function takes the object of **Illuminate\\Support\\Collection** instead of **Illuminate\\Http\\Request**. This will allow you to use this function in any tier of the code.\n\nAlso, the 'guard' name reference is passed, so that you can reuse the function for multiple guard drivers in your project. The function has the capability to handle the Session and Token Guards with multiple drivers and providers as defined in /config/auth.php\n\n```php\n\n    namespace Ellaisys\\Cognito\\Auth;\n\n    protected function attemptLogin (\n        Collection $request, string $guard='web', \n        string $paramUsername='email', string $paramPassword='password', \n        bool $isJsonResponse=false\n    ) {\n        ...\n        ...\n\n\n        ...\n    }\n\n```\n\nIn case you want to use this trait for Web login, you can write the code as shown below in the AuthController.php\n\n```php\n\n    namespace App\\Http\\Controllers;\n\n    ...\n\n    use Ellaisys\\Cognito\\AwsCognitoClaim;\n    use Ellaisys\\Cognito\\Auth\\AuthenticatesUsers as CognitoAuthenticatesUsers;\n\n    class AuthController extends Controller\n    {\n        use CognitoAuthenticatesUsers;\n\n        /**\n         * Authenticate User\n         * \n         * @throws \\HttpException\n         * \n         * @return mixed\n         */\n        public function login(\\Illuminate\\Http\\Request $request)\n        {\n            ...\n\n            //Convert request to collection\n            $collection = collect($request-\u003eall());\n\n            //Authenticate with Cognito Package Trait (with 'web' as the auth guard)\n            if ($response = $this-\u003eattemptLogin($collection, 'web')) {\n                if ($response===true) {\n                    return redirect(route('home'))-\u003ewith('success', true);\n                } else if ($response===false) {\n                    // If the login attempt was unsuccessful you may increment the number of attempts\n                    // to login and redirect the user back to the login form. Of course, when this\n                    // user surpasses their maximum number of attempts they will get locked out.\n                    //\n                    //$this-\u003eincrementLoginAttempts($request);\n                    //\n                    //$this-\u003esendFailedLoginResponse($collection, null);\n                } else {\n                    return $response;\n                } //End if\n            } //End if\n\n        } //Function ends\n\n        ...\n    } //Class ends\n\n```\n\nIn case you want to use this trait for API based login, you can write the code as shown below in the AuthApiController.php\n\n```php\n\n    namespace App\\Api\\Controller;\n\n    ...\n\n    use Ellaisys\\Cognito\\AwsCognitoClaim;\n    use Ellaisys\\Cognito\\Auth\\AuthenticatesUsers as CognitoAuthenticatesUsers;\n\n    class AuthApiController extends Controller\n    {\n        use CognitoAuthenticatesUsers;\n\n        /**\n         * Authenticate User\n         * \n         * @throws \\HttpException\n         * \n         * @return mixed\n         */\n        public function login(\\Illuminate\\Http\\Request $request)\n        {\n            ...\n\n            //Convert request to collection\n            $collection = collect($request-\u003eall());\n\n            //Authenticate with Cognito Package Trait (with 'api' as the auth guard)\n            if ($claim = $this-\u003eattemptLogin($collection, 'api', 'username', 'password', true)) {\n                if ($claim instanceof AwsCognitoClaim) {\n                    return $claim-\u003egetData();\n                } else {\n                    return response()-\u003ejson(['status' =\u003e 'error', 'message' =\u003e $claim], 400);\n                } //End if\n            } //End if\n\n        } //Function ends\n\n\n        ...\n    } //Class ends\n\n```\n\n## Signout (Remove Access Token)\n\nThe logout methods are now part of the guard implementations, the logout method removes the access-tokens from AWS and also removes from Application Storage managed by this library. Just calling the auth guard logout method will be sufficient. You can implement it into the routes or controller based on your development preference.\n\nThe logout method now takes an **optional** boolean parameter (true) to revoke RefreshToken. The default value is (false) and that will persist the Refresh Token with AWS Cognito.\n\n```php\n\n   ...\n\n   Auth::guard('api')-\u003elogout();\n\n\n   ...\n\n   Auth::guard('api')-\u003elogout(true); //Revoke the Refresh Token.\n\n```\n\n\n## Refresh Token\n\nYou can use this trait for API to generate new token\n\n```php\n\n    namespace App\\Api\\Controller;\n\n    ...\n\n    use Ellaisys\\Cognito\\AwsCognitoClaim;\n    use Ellaisys\\Cognito\\Auth\\RefreshToken;\n\n    class AuthApiController extends Controller\n    {\n        use RefreshToken;\n\n        /**\n         * Generate a new token using refresh token.\n         * \n         * @throws \\HttpException\n         * \n         * @return mixed\n         */\n        public function refreshToken(\\Illuminate\\Http\\Request $request)\n        {\n            ...\n\n            $validator = $request-\u003evalidate([\n                'email' =\u003e 'required|email',\n                'refresh_token' =\u003e 'required'\n            ]);\n            \n            try {\n                return $this-\u003erefresh($request, 'email', 'refresh_token');\n            } catch (Exception $e) {\n                return $e;\n            }\n\n        } //Function ends\n\n\n        ...\n    } //Class ends\n\n```\n\n\n## Delete User\n\nIf you want to give your users the ability to delete themselves from your app you can use our deleteUser function\nfrom the CognitoClient.\n\nTo delete the user you should call deleteUser and pass the email of the user as a parameter to it.\nAfter the user has been deleted in your cognito pool, delete your user from your database too.\n\n```php\n        $cognitoClient-\u003edeleteUser($user-\u003eemail);\n        $user-\u003edelete();\n```\n\nWe have implemented a new config option `delete_user`, which you can access through `AWS_COGNITO_DELETE_USER` env var.\nIf you set this config to true, the user is deleted in the Cognito pool. If it is set to false, it will stay registered.\nPer default this option is set to false. If you want this behaviour you should set USE_SSO to true to let the user\nrestore themselves after a successful login.\n\nTo access our CognitoClient you can simply pass it as a parameter to your Controller Action where you want to perform\nthe deletion.\n\n```php\n    public function deleteUser(Request $request, AwsCognitoClient $client)\n```\n\nLaravel will take care of the dependency injection by itself.\n\n```\n    IMPORTANT: You want to secure this action by maybe security questions, a second delete password or by confirming \n    the email address.\n```\n\n## Storing Web Sessions or API Tokens in DynamoDB (Useful for multiserver/container implementation)\n\nIf you have a deployment architecture, that involves multiple servers and you want to maintain the web sessions or API tokens across the servers, you can use the AWS DynamoDB. The library is capable of handling the DynamoDB with ease. All that you need to do is create the table in AWS DynamoDB and change a few configurations.\n\n### Creating a new table in AWS DynamoDB\n1. Go to the AWS Console and create a new table.\n2. Enter the unique table name as per your preferences.\n3. The primary key (or partition key) should be **key** of type **string**\n4. Use default settings and click the **Create** button\n\n### Update the .env file for Dynamo DB configurations\nAdd/Edit the following fields to your `.env` file and set the values according to your AWS settings:\n\n```php\n\n    # Cache Configuration\n    CACHE_DRIVER=\"dynamodb\"\n    DYNAMODB_CACHE_TABLE=\"table-name-of-your-choice\" //This should match the table name provided above\n\n    # Session Configuration\n    SESSION_DRIVER=\"dynamodb\"\n    SESSION_LIFETIME=120\n    SESSION_DOMAIN=\"set-your-domain-name\" //The domain name can be as per your preference\n    SESSION_SECURE_COOKIE=true\n\n    # DynamoDB Configuration\n    DYNAMODB_ENDPOINT=\"https://dynamodb.us-west-2.amazonaws.com\" // You can change the endpoint based of different regions\n\n```\n\nRefer the [AWS DynamoDB Documentation](https://docs.aws.amazon.com/general/latest/gr/ddb.html) and refer the endpoints provided in **Service endpoints** section.\n\nUpdate the DynamoDB table for the TTL columns as **expires_at**\n\n\n## Automatic User Password update for API usage (for New Cognito Users)\n\nIn case of the new cognito users, the AWS SDK will send a session key and the user is expected to change the password, in a forced mode. Make sure you force the users to change the password for the first login by new cognito user.\n\nHowever, if you have an API based implementation, and want to automatically authenticate the user without forcing the password change, you may do that with below setting fields to your `.env` file\n\n```php\n\n    AWS_COGNITO_FORCE_PASSWORD_CHANGE_API=false     //Make true for forcing password change\n    AWS_COGNITO_FORCE_PASSWORD_AUTO_UPDATE_API=true //Make false for stopping auto password change\n\n```\n\n## Support for App Client without Secret enabled\n\nThe library now supports where the AWS configuration of App Client with the Client Secret set to disabled. Use the below configuration into the environment file to enable/disable this. The default is marked as enable (i.e. we expect the App Client Secret to be enabled in AWS Cognito configuration)\n\n```php\n\n   AWS_COGNITO_CLIENT_SECRET_ALLOW=false\n\n```\n\n## Password Validation based of Cognito Configuration\n\nThis library fetches the password policy from the cognito pool configurations. The laravel request validations are done based on the regular expression that is created based on this policy. This validations are performed during the Sign Up (Registation), Sign In (Login), Reset and Change password based flows. The validation messages for the password are also dynamic in nature and change based on the configurations.\n\n\u003e[!IMPORTANT]\n\u003eIn case of special characters, we are supporting all except the pipe character **|** for now.\n\n## Mapping Cognito User using Subject UUID\n\nThe library maps the Cognito user subject UUID with the local repository. Everytime a new user is created in cognito, the sub UUID is mapped with the local user table with an user specified column name.\n\nThe column in the local BD is identified with the config parameter `user_subject_uuid` with the default value set to `sub`.\n\nHowever, to customize the column name in the local DB user table, you may do that with below setting fields to your `.env` file\n\n```php\n\n    AWS_COGNITO_USER_SUBJECT_UUID=\"sub\"\n    \n```\n\nWe are working on making sure that pipe character is handled soon.\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Security\n\nIf you discover any security related issues, please email [support@ellaisys.com](mailto:support@ellaisys.com) and also add it to the issue tracker.\n\n## Roadmap\n\nhttps://github.com/ellaisys/aws-cognito/wiki/RoadMap\n\n## How to contribute\n\n- Star this project on GitHub.\n- Report bugs or suggest features by creating new issues or adding comments to issues\n- Submit pull requests\n- Spread the word by blogging about SimplCommerce or sharing it on social networks\n- Donate to us\n\n## Credits \u0026 Contributors\n\nThis project exists thanks to all the people who contribute.\n\n- [EllaiSys Team](https://github.com/ellaisys)\n- [GitHub Contributors](https://github.com/ellaisys/aws-cognito/graphs/contributors)\n\nClick on these badges to see how you might be able to help:\n\n\u003cdiv align=\"center\" markdown=\"1\"\u003e\n\n[![GitHub repo Issues](https://img.shields.io/github/issues/ellaisys/aws-cognito?style=flat\u0026logo=github\u0026logoColor=red\u0026label=Issues)](https://github.com/ellaisys/aws-cognito/issues)\u0026#160;\n[![GitHub repo Good Issues for newbies](https://img.shields.io/github/issues/ellaisys/aws-cognito/good%20first%20issue?style=flat\u0026logo=github\u0026logoColor=green\u0026label=Good%20First%20issues)](https://github.com/ellaisys/aws-cognito/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)\u0026#160;\n[![GitHub Help Wanted issues](https://img.shields.io/github/issues/ellaisys/aws-cognito/help%20wanted?style=flat\u0026logo=github\u0026logoColor=b545d1\u0026label=%22Help%20Wanted%22%20issues)](https://github.com/ellaisys/aws-cognito/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22)    \n[![GitHub repo PRs](https://img.shields.io/github/issues-pr/ellaisys/aws-cognito?style=flat\u0026logo=github\u0026logoColor=orange\u0026label=PRs)](https://github.com/ellaisys/aws-cognito/pulls)\u0026#160;\n[![GitHub repo Merged PRs](https://img.shields.io/github/issues-search/ellaisys/aws-cognito?style=flat\u0026logo=github\u0026logoColor=green\u0026label=Merged%20PRs\u0026query=is%3Amerged)](https://github.com/ellaisys/aws-cognito/pulls?q=is%3Apr+is%3Amerged)\u0026#160;\n[![GitHub Help Wanted PRs](https://img.shields.io/github/issues-pr/ellaisys/aws-cognito/help%20wanted?style=flat\u0026logo=github\u0026logoColor=b545d1\u0026label=%22Help%20Wanted%22%20PRs)](https://github.com/ellaisys/aws-cognito/pulls?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22)\n\u003c/div\u003e\n\n## Support us\n\nEllaiSys was a web and consulting agency specialized in Cloud Computing (AWS and Azure), DevOps, and Product Engneering. We closed our professional services offerings from Oct 2021, however the team continues to support the open source projects as our commitment towards the community. Anyone interested to support the development is welcome.\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n\n## Disclaimer\n_This package is currently in production ready mode with already a few implementations done. We would be happy to hear from you, about the defects or new feature enhancements. However, this being a free support, we would not be able to commit to support SLAs or timelines._\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fellaisys%2Faws-cognito","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fellaisys%2Faws-cognito","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fellaisys%2Faws-cognito/lists"}