Using Developer Authenticated Identities with Cognito Identity Pools In TypeScript

Cognito identity pools provide an easy way to enable your users to have limited access to your AWS backend. With developer authenticated identities, you can integrate Cognito into your existing authentication process.

1. Create an Identity Pool

Go to the Cognito developers console and click “Manage Identity Pools,” then “Create new identity pool.” Name your app, and decide if you want to enable unauthenticated identities.

Next, expand the “Authentication providers” dropdown and select the “custom” tab. Provide a developer authenticated name for your backend. This can be any string, but remember, you cannot change it after setting it. This will be used by your backend to identify itself.

Clicking “Create Pool” prompts you to set up IAM roles for your users. Make sure to do this, or your users won’t have access to any AWS resources.

2. Backend Setup

In order to create a Cognito identity, you will need credentials from your own identity provider. After creating your credentials, you can create a Cognito identity using the GetOpenIdTokenForDeveloperIdentity api call. Here’s an example in TypeScript:


...
const identityClient = new CognitoIdentity();

const params = ( credentials: string ): CognitoIdentity.GetOpenIdTokenForDeveloperIdentityInput => ({ IdentityPoolId: "<YOU-COGNITO-IDENTITY-POOL-ID>", Logins: { "<YOUR-DEVELOPER-AUTHENTICATED-NAME>": credentials } }); const openIdRequest = await identityClient .getOpenIdTokenForDeveloperIdentity(params(deviceHashCode)) .promise(); ...

Make sure to return the cognitoToken and the identityId from the GetOpenIdTokenForDeveloperIdentity call to your client. These are used to grant your client access to AWS resources.

3. Frontend Setup

Now that you have an identity id and a token from Cognito, you can set up your credentials on the frontend. Here’s an example in TypeScript:


import * as AWS from "aws-sdk";
AWS.config.region = "<YOUR-AWS-REGION>";
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: "<IDENTITY-POOL-ID>",
    IdentityId: "<IDENTITY-ID-RETURNED-FROM-YOUR-BACKEND>",
    Logins: {
        "cognito-identity.amazonaws.com": "<COGNITO-TOKEN-RETURNED-BY-SERVER>"
    }
});

That’s it! You should now be able to make authorized requests to AWS resources.