PHPackages                             shady-amir/laravel-aws-cognito-auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. shady-amir/laravel-aws-cognito-auth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

shady-amir/laravel-aws-cognito-auth
===================================

An authentication driver for Laravel for authenticating users in AWS Cognito User Pools with group and roles with AWS API gateway helper functions.

v1.2.2(6y ago)03.1kMITPHPPHP &gt;= 5.6.4

Since Apr 24Pushed 6y agoCompare

[ Source](https://github.com/SaW-/laravel-aws-cognito-auth)[ Packagist](https://packagist.org/packages/shady-amir/laravel-aws-cognito-auth)[ RSS](/packages/shady-amir-laravel-aws-cognito-auth/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (2)Dependencies (2)Versions (9)Used By (0)

Laravel AWS Cognito Auth
========================

[](#laravel-aws-cognito-auth)

This package is forked from [ArranJacques/laravel-aws-cognito-auth](https://github.com/ArranJacques/laravel-aws-cognito-auth).

A simple authentication package for Laravel 5 for authenticating users in Amazon Cognito User Pools with group and roles with AWS API gateway helper functions.

This is package works with Laravel's native authentication system and allows the authentication of users that are already registered in Amazon Cognito User Pools, get user groups and roles and change password for first time login only. It does not provide functionality for user management, i.e., registering user's into User Pools, password resets, etc.

### Contents

[](#contents)

- [Installation and Setup](#installation-and-setup)
    - [Install](#install)
    - [Configure](#configure)
    - [Users Table](#users-table)
- [Usage](#usage)
    - [Authenticating](#authenticating)
    - [AWS API Gateway](#aws-api-gateway)
    - [Handling Failed Authentication](#handling-failed-authentication)
        - [Methods](#methods)
            - [No Error Handling](#no-error-handling)
            - [Throw Exception](#throw-exception)
            - [Return Attempt Instance](#return-attempt-instance)
            - [Using a Closure](#using-a-closure)
            - [Using a Custom Class](#using-a-custom-class)
        - [Default Error Handler](#default-error-handler)
        - [About AuthAttemptException](#about-authattemptexception)

Installation and Setup
----------------------

[](#installation-and-setup)

This package makes use of the [aws-sdk-php-laravel](https://github.com/aws/aws-sdk-php-laravel) package. As well as setting up and configuring this package you'll also need to configure [aws-sdk-php-laravel](https://github.com/aws/aws-sdk-php-laravel) for the authentication to work. Instructions on how to do this are below. If you've already installed, set up and configured [aws-sdk-php-laravel](https://github.com/aws/aws-sdk-php-laravel) you can skip the parts where it's mentioned below.

### Install

[](#install)

Add `pallant/laravel-aws-cognito-auth` to `composer.json` and run `composer update` to pull down the latest version:

```
"shady-amir/laravel-aws-cognito-auth": "~1.2.2"

```

Or use `composer require`:

```
composer require shady-amir/laravel-aws-cognito-auth

```

Add the service provider and the [aws-sdk-php-laravel](https://github.com/aws/aws-sdk-php-laravel) service provider to the `providers` array in `config/app.php`.

```
'providers' => [
    ...
    Aws\Laravel\AwsServiceProvider::class,
    Pallant\LaravelAwsCognitoAuth\ServiceProvider::class,
    ...
]
```

Open `app/Http/Kernel.php` and replace the default `\Illuminate\Session\Middleware\AuthenticateSession::class` middleware with `\Pallant\LaravelAwsCognitoAuth\AuthenticateSession::class`.

```
protected $middlewareGroups = [
    'web' => [
        ...
        \Pallant\LaravelAwsCognitoAuth\AuthenticateSession::class,
        ...
    ],
];
```

Publish the config file as well as the [aws-sdk-php-laravel](https://github.com/aws/aws-sdk-php-laravel) config file to your `config` directory by running:

```
php artisan vendor:publish --provider="Pallant\LaravelAwsCognitoAuth\ServiceProvider"

php artisan vendor:publish --provider="Aws\Laravel\AwsServiceProvider"

```

### Configure

[](#configure)

Open `config/auth.php` and set your default guard's driver to `aws-cognito`. Out of the box the default guard is `web` so your `config/auth.php` would look something like:

```
'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

...

'guards' => [
    'web' => [
        'driver' => 'aws-cognito',
        'provider' => 'users',
    ],
]
```

Open `config/aws-cognito-auth.php` and add your AWS Cognito User Pool's id, and User Pool App's `client-id`.

```
'pool-id' => '',

...

'apps' => [
    'default' => [
        'client-id' => '',
        'refresh-token-expiration' => 30,
    ],
]
```

When creating an App for your User Pool the default Refresh Token Expiration time is 30 days. If you've set a different expiration time for your App then make sure you update the `refresh-token-expiration` value in the config file accordingly.

```
'apps' => [
    'default' => [
        'client-id' => '',
        'refresh-token-expiration' => ,
    ],
]
```

Open the `config/aws.php` file and set the `region` value to whatever region your User Pool is in. The default `config/aws.php` file that is created when using the `php artisan vendor:publish --provider="Aws\Laravel\AwsServiceProvider"` command doesn't include the IAM credential properties so you'll need to add them manually. Add the following to the `config/aws.php` file where `key` is an IAM user Access Key Id and `secret` is the corresponding Secret key:

```
'credentials' => [
    'key' => ,
    'secret' => ,
]
```

Your final `config/aws.php` should look something like this:

```
'credentials' => [
    'key' => ,
    'secret' => ,
],
'region' => ,
'version' => 'latest',
'ua_append' => [
    'L5MOD/' . AwsServiceProvider::VERSION,
],
```

### Users Table

[](#users-table)

Cognito is not treated as a "database of users", and is only used to authorise the users. A request to Cognito is not made unless the user already exists in the app's database. This means you'll still need a `users` table populated with the users that you want to authenticate. At a minimum this table will need an `id`, `email` and `remember_token` field.

In Cognito every user has a `username`. When authenticating with Cognito this package will need one of the user's attributes to match the user's Congnito username. By default it uses the user's `email` attribute.

If you want to use a different attribute to store the user's Cognito username then you can do so by first adding a new field to your `users` table, for example `cognito_username`, and then setting the `username-attribute` in the `config/aws-cognito-auth.php` file to be the name of that field.

Note: It will create user in local database if user if NOT exit.

Usage
-----

[](#usage)

Once installed and configured authentication works the same as it doesn natively in Laravel. See Laravel's [documentation](https://laravel.com/docs/5.4/authentication) for full details.

### Authenticating

[](#authenticating)

**Authenticate:**

```
Auth::attempt([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
]);
```

**Authenticate and remember:**

```
Auth::attempt([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], true);
```

**Change Password for ChallengeName = NEW\_PASSWORD\_REQUIRED :**

```
Auth::confirmPassword([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
    'session' => 'xxxxxxxxxx',
]);
```

**Get the authenticated user:**

```
Auth::user();
```

**Logout:**

```
Auth::logout();
```

As well as the default functionality some extra methods are made available for accessing the user's Cognito access token, id token, etc:

```
Auth::getCognitoAccessToken();
```

```
Auth::getCognitoIdToken();
```

```
Auth::getCognitoRefreshToken();
```

```
Auth::getCognitoTokensExpiryTime();
```

```
Auth::getCognitoRefreshTokenExpiryTime();
```

```
Auth::getCognitoAccessRoles();
```

```
Auth::getCognitoAccessGroups();
```

```
Auth::hasCognitoAccessRole($role)
```

```
Auth::hasCognitoAccessGroup($group)
```

### AWS API Gateway

[](#aws-api-gateway)

**Example:**

```
use Pallant\LaravelAwsCognitoAuth\Utilities\AwsSecureRequest;

$region = env('AWS_GETWAY_API_REGION');
$version = env('AWS_GETWAY_API_VERSION');
$IdentityPoolId = env('AWS_GETWAY_API_IDENTITY_POOL_ID');
$Logins = env('AWS_GETWAY_API_LOGINS');
$awsSecureRequest = new AwsSecureRequest($region, $version, $IdentityPoolId, $Logins);

$host = 'AWS_HOST_API_GATEWAY_WITHOUT_HTTPS';
$uri = 'URI_TO_API_CALL';
$QueryString = '';
$httpRequestMethod = 'GET';
$postData = [];
$awsService = 'execute-api'
$userIdToken = 'idToken'; // Auth::getCognitoIdToken();
$debug = TRUE;

$result = $this->awsSecureRequest->SignatureAndCallAPI($host, $uri, $awsService, $httpRequestMethod, $QueryString, $postData, $userIdToken,$debug);
```

### Handling Failed Authentication

[](#handling-failed-authentication)

AWS Cognito may fail to authenticate for a number of reasons, from simply entering the wrong credentials, or because additional checks or actions are required before the user can be successfully authenticated.

So that you can deal with failed attempts appropriately several options are available to you within the package that dictate how failed attempts should be handled.

#### Methods

[](#methods)

You can specify how failed attempts should be handled by passing an additional `$errorHandler` argument when calling the `Auth::attempt()` and `Auth::validate()` methods.

```
Auth::attempt(array $credentials, [bool $remember], [$errorHandler]);

Auth::validate(array $credentials, [$errorHandler]);
```

##### No Error Handling

[](#no-error-handling)

If an `$errorHandler` isn't passed then all failed authentication attempts will be handled and suppressed internally, and both the `Auth::attempt()` and `Auth::validate()` methods will simply return `true` or `false` as to whether the authentication attempt was successful.

##### Throw Exception

[](#throw-exception)

To have the `Auth::attempt()` and `Auth::validate()` methods throw an exception pass `AWS_COGNITO_AUTH_THROW_EXCEPTION` as the `$errorHandler` argument.

```
Auth::attempt([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], false, AWS_COGNITO_AUTH_THROW_EXCEPTION);

Auth::validate([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], AWS_COGNITO_AUTH_THROW_EXCEPTION);
```

If the authentication fails then a `\Pallant\LaravelAwsCognitoAuth\AuthAttemptException` exception will be thrown, which can be used to access the underlying error by calling the exception's `getResponse()` method. [About AuthAttemptException](#about-authattemptexception).

```
try {
    Auth::attempt([
        'email' => 'xxxxx@xxxxx.xx',
        'password' => 'xxxxxxxxxx',
    ], false, AWS_COGNITO_AUTH_THROW_EXCEPTION);
} catch (\Pallant\LaravelAwsCognitoAuth\AuthAttemptException $e) {
    $response = $e->getResponse();
    // Handle error...
}
```

##### Return Attempt Instance

[](#return-attempt-instance)

To have the `Auth::attempt()` and `Auth::validate()` methods return an attempt object pass `AWS_COGNITO_AUTH_RETURN_ATTEMPT` as the `$errorHandler` argument.

```
Auth::attempt([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], false, AWS_COGNITO_AUTH_RETURN_ATTEMPT);

Auth::validate([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], AWS_COGNITO_AUTH_RETURN_ATTEMPT);
```

When using `AWS_COGNITO_AUTH_RETURN_ATTEMPT` both methods will return an instance of `\Pallant\LaravelAwsCognitoAuth\AuthAttempt`, which can be used to check if the authentication attempt was successful or not.

```
$attempt = Auth::attempt([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], false, AWS_COGNITO_AUTH_RETURN_ATTEMPT);

if ($attempt->successful()) {
    // Do something...
} else {
    $response = $attempt->getResponse();
    // Handle error...
}
```

For unsuccessful authentication attempts the attempt instance's `getResponse()` method can be used to access the underlying error. This method will return an array of data that will contain different values depending on the reason for the failed attempt.

In events where the AWS Cognito API has thrown an exception, such as when invalid credentials are used, the array that is returned will contain the original exception.

```
[
    'exception' => CognitoIdentityProviderException {...},
]
```

In events where the AWS Cognito API has failed to authenticate for some other reason, for example because a challenge must be passed, then the array that is returned will contain the details of the error.

```
[
    'ChallengeName' => 'NEW_PASSWORD_REQUIRED',
    'Session' => '...',
    'ChallengeParameters' => [...],
]
```

##### Using a Closure

[](#using-a-closure)

To handle failed authentication attempts with a closure pass one as the `Auth::attempt()` and `Auth::validate()` methods' `$errorHandler` argument.

```
Auth::attempt([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], false, function (\Pallant\LaravelAwsCognitoAuth\AuthAttemptException $e) {
    $response = $e->getResponse();
    // Handle error...
});

Auth::validate([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], function (\Pallant\LaravelAwsCognitoAuth\AuthAttemptException $e) {
    $response = $e->getResponse();
    // Handle error...
};
```

If the authentication fails then the closure will be run and will be passed an `\Pallant\LaravelAwsCognitoAuth\AuthAttemptException` instance, which can be used to access the underlying error by calling the exception's `getResponse()` method. [About AuthAttemptException](#about-authattemptexception).

##### Using a Custom Class

[](#using-a-custom-class)

To handle failed authentication attempts with a custom class pass the classes name as the `Auth::attempt()` and `Auth::validate()` methods' `$errorHandler` argument.

```
Auth::attempt([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], false, \App\MyCustomErrorHandler::class);

Auth::validate([
    'email' => 'xxxxx@xxxxx.xx',
    'password' => 'xxxxxxxxxx',
], \App\MyCustomErrorHandler::class);
```

The error handler class should have a `handle()` method, which will be called when an authentication attempt fails. The `handle()` method will be passed an `\Pallant\LaravelAwsCognitoAuth\AuthAttemptException` instance, which can be used to access the underlying error by calling the exception's `getResponse()` method. [About AuthAttemptException](#about-authattemptexception).

```
