Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

Advanced workflows

Subscribing to Events

You can take specific actions when users sign-in or sign-out by subscribing to authentication events in your app. Please see our Hub Module Developer Guide for more information.

Identity Pool Federation

You can alternatively create your own custom credentials provider to get AWS credentials directly from Cognito Federated Identities and not use User Pool federation. You must supply the custom credentials provider to Amplify via the Amplify.configure method call. Below, you can see sample code of how such a custom provider can be built to achieve the use case.

import { Amplify } from 'aws-amplify';
import {
fetchAuthSession,
CredentialsAndIdentityIdProvider,
CredentialsAndIdentityId,
GetCredentialsOptions,
AuthTokens,
} from 'aws-amplify/auth';
// Note: This example requires installing `@aws-sdk/client-cognito-identity` to obtain Cognito credentials
// npm i @aws-sdk/client-cognito-identity
import { CognitoIdentity } from '@aws-sdk/client-cognito-identity';
// You can make use of the sdk to get identityId and credentials
const cognitoidentity = new CognitoIdentity({
region: '<region-from-config>',
});
// Note: The custom provider class must implement CredentialsAndIdentityIdProvider
class CustomCredentialsProvider implements CredentialsAndIdentityIdProvider {
// Example class member that holds the login information
federatedLogin?: {
domain: string,
token: string
};
// Custom method to load the federated login information
loadFederatedLogin(login?: typeof this.federatedLogin) {
// You may also persist this by caching if needed
this.federatedLogin = login;
}
async getCredentialsAndIdentityId(
getCredentialsOptions: GetCredentialsOptions
): Promise<CredentialsAndIdentityId | undefined> {
try {
// You can add in some validation to check if the token is available before proceeding
// You can also refresh the token if it's expired before proceeding
const getIdResult = await cognitoidentity.getId({
// Get the identityPoolId from config
IdentityPoolId: '<identity-pool-id-from-config>',
Logins: { [this.federatedLogin.domain]: this.federatedLogin.token },
});
const cognitoCredentialsResult = await cognitoidentity.getCredentialsForIdentity({
IdentityId: getIdResult.IdentityId,
Logins: { [this.federatedLogin.domain]: this.federatedLogin.token },
});
const credentials: CredentialsAndIdentityId = {
credentials: {
accessKeyId: cognitoCredentialsResult.Credentials?.AccessKeyId,
secretAccessKey: cognitoCredentialsResult.Credentials?.SecretKey,
sessionToken: cognitoCredentialsResult.Credentials?.SessionToken,
expiration: cognitoCredentialsResult.Credentials?.Expiration,
},
identityId: getIdResult.IdentityId,
};
return credentials;
} catch (e) {
console.log('Error getting credentials: ', e);
}
}
// Implement this to clear any cached credentials and identityId. This can be called when signing out of the federation service.
clearCredentialsAndIdentityId(): void {}
}
// Create an instance of your custom provider
const customCredentialsProvider = new CustomCredentialsProvider();
Amplify.configure(awsconfig, {
Auth: {
// Supply the custom credentials provider to Amplify
credentialsProvider: customCredentialsProvider
},
});

Now that the custom credentials provider is built and supplied to Amplify.configure, let's look at how you can use the custom credentials provider to finish federation into Cognito identity pool.

Facebook sign-in (React)

import React, { useEffect } from 'react';
import {
fetchAuthSession,
} from 'aws-amplify/auth';
// To federated sign in from Facebook
const SignInWithFacebook = () => {
useEffect(() => {
if (!window.FB) createScript();
}, [])
const signIn = () => {
const fb = window.FB;
fb.getLoginStatus(response => {
if (response.status === 'connected') {
getAWSCredentials(response.authResponse);
} else {
fb.login(
response => {
if (!response || !response.authResponse) {
return;
}
customCredentialsProvider.loadFederatedLogin({
domain: 'graph.facebook.com',
token: response.authResponse.accessToken,
});
const fetchSessionResult = await fetchAuthSession(); // will return the credentials
console.log('fetchSessionResult: ', fetchSessionResult);
},
{
// the authorized scopes
scope: 'public_profile,email'
}
);
}
});
}
const createScript = () => {
// load the sdk
window.fbAsyncInit = fbAsyncInit;
const script = document.createElement('script');
script.src = 'https://connect.facebook.net/en_US/sdk.js';
script.async = true;
script.onload = initFB;
document.body.appendChild(script);
}
const initFB = () => {
const fb = window.FB;
console.log('FB SDK initialized');
}
const fbAsyncInit = () => {
// init the fb sdk client
const fb = window.FB;
fb.init({
appId : 'your_facebook_app_id',
cookie : true,
xfbml : true,
version : 'v2.11'
});
}
return (
<div>
<button onClick={signIn}>Sign in with Facebook</button>
</div>
);
}

Google sign-in (React)

import React, { useEffect } from 'react';
import jwt from 'jwt-decode';
import {
fetchAuthSession,
} from 'aws-amplify/auth';
const SignInWithGoogle = () => {
useEffect(() => {
// Check for an existing Google client initialization
if (!window.google?.accounts) createScript();
}, []);
// Load the Google client
const createScript = () => {
const script = document.createElement('script');
script.src = 'https://accounts.google.com/gsi/client';
script.async = true;
script.defer = true;
script.onload = initGsi;
document.body.appendChild(script);
}
// Initialize Google client and render Google button
const initGsi = () => {
if (window.google?.accounts) {
window.google.accounts.id.initialize({
client_id: process.env.GOOGLE_CLIENT_ID,
callback: (response: any) => {
customCredentialsProvider.loadFederatedLogin({
domain: 'accounts.google.com',
token: response.credential,
});
const fetchSessionResult = await fetchAuthSession(); // will return the credentials
console.log('fetchSessionResult: ', fetchSessionResult);
},
});
window.google.accounts.id.renderButton(
document.getElementById('googleSignInButton'),
{ theme: 'outline', size: 'large' }
);
}
}
return (
<div>
<button id='googleSignInButton'/>
</div>
);
}

Federate with Auth0

You can use Auth0 as one of the providers of your Cognito Identity Pool. This will allow users authenticated via Auth0 have access to your AWS resources.

Step 1. Follow Auth0 integration instructions for Cognito Federated Identity Pools

Step 2. Login with Auth0, then use the id token returned to get AWS credentials from Cognito Federated Identity Pools using custom credentials provider you created at the start:

import { fetchAuthSession } from 'aws-amplify/auth';
const { idToken, domain, name, email, phoneNumber } = getFromAuth0(); // get the user credentials and info from auth0
async function getCognitoCredentials() {
try {
customCredentialsProvider.loadFederatedLogin({
domain,
token: idToken
});
const fetchSessionResult = await fetchAuthSession(); // will return the credentials
console.log('fetchSessionResult: ', fetchSessionResult);
} catch (err) {
console.log(err);
}
}

Lambda Triggers

The CLI allows you to configure Lambda Triggers for your Cognito User Pool. These enable you to add custom functionality to your registration and authentication flows. Read more

Pre Authentication and Pre Sign-up Lambda triggers

If you have a Pre Authentication Lambda trigger enabled, you can pass clientMetadata as an option for signIn. This metadata can be used to implement additional validations around authentication.

import { signIn } from 'aws-amplify/auth';
async function handleSignIn(username: string, password: string) {
try {
await signIn({
username,
password,
options: {
clientMetadata: {} // Optional, an object of key-value pairs which can contain any key and will be passed to your Lambda trigger as-is.
}
});
} catch (err) {
console.log(err);
}
}

Passing metadata to other Lambda triggers

Many Cognito Lambda Triggers also accept unsanitized key/value pairs in the form of a clientMetadata attribute. This attribute can be specified for various Auth APIs which result in Cognito Lambda Trigger execution.

These APIs include:

  • signIn
  • signUp
  • confirmSignIn
  • confirmSignUp
  • resetPassword
  • confirmResetPassword
  • resendSignUpCode
  • updateUserAttributes

Please note that some of triggers which accept a validationData attribute will use clientMetadata as the value for validationData. Exercise caution with using clientMetadata when you are relying on validationData.

Working with AWS service objects

You can use AWS Service Interface Objects to work with AWS Services in authenticated State. You can call methods on any AWS Service interface object by passing your credentials from Amplify fetchAuthSession to the service call constructor:

import { fetchAuthSession } from 'aws-amplify/auth';
import Route53 from 'aws-sdk/clients/route53';
async function changeResourceRecordSets() {
try {
const { credentials } = await fetchAuthSession();
const route53 = new Route53({
apiVersion: '2013-04-01',
credentials
});
// more code working with route53 object
//route53.changeResourceRecordSets();
} catch (err) {
console.log(err);
}
}

Note: To work with Service Interface Objects, your Amazon Cognito users' IAM role must have the appropriate permissions to call the requested services.

Custom Token providers

Create a custom Auth token provider for situations where you would like provide your own tokens for a service. For example, using OIDC Auth with AppSync. You must supply the token provider to Amplify via the Amplify.configure method call. Below, you can see sample code of how such a custom provider can be built to achieve the use case.

import { Amplify } from 'aws-amplify';
import { TokenProvider, decodeJWT } from 'aws-amplify/auth';
// ...
const myTokenProvider: TokenProvider = {
async getTokens({ forceRefresh } = {}) {
if (forceRefresh) {
// try to obtain new tokens if possible
}
const accessTokenString = '<insert JWT from provider>';
const idTokenString = '<insert JWT from provider>';
return {
accessToken: decodeJWT(accessTokenString),
idToken: decodeJWT(idTokenString),
};
},
};
Amplify.configure(awsconfig, {
Auth: {
tokenProvider: myTokenProvider
}
});

API reference

For the complete API documentation for Authentication module, visit our API Reference