Using Auth0 as OIDC provider for Cognito Identity Pool

Gunjan Chhetri - Aug 24 - - Dev Community

In a previous post Authentication and Authorization with AWS Cognito, we explored how to securely grant users access to AWS resources by leveraging AWS Cognito User Pools and Identity Pools. In that scenario, the User Pool handled authentication, and upon successful login, the Identity Pool provided the necessary temporary credentials, allowing access to services like Amazon Kinesis.

In this post, we will take a step further and replace the Cognito User Pool with Auth0 for authentication. This approach is particularly useful if you prefer Auth0’s robust and feature-rich authentication services. We will walk through the steps to integrate Auth0 with an AWS Cognito Identity Pool, enabling authenticated users to access AWS resources securely.

The full code can be found here https://github.com/gunjchhetri/autho_cognito_identity

Create an application in Auth0
The first step is to create an application in Auth0, which serves as the identity provider for the users.

  • Create a New Application: Go to Auth0 dashboard and click on the "Applications" section and create a new application. You will need to select the type of application (e.g., Single Page Application, Native, etc.) based on your use case. For this demo we will be creating Single Page Application.
  • Retrieve Application Domain and Client ID: Once the application is created, note down the Domain and Client ID—these will be used in later steps.

For detailed instructions, refer to the https://auth0.com/docs/get-started/auth0-overview/create-applications

Create Custom Identity Provider
Next, we need to set up an OpenID Connect (OIDC) identity provider in AWS IAM, where we provide the details of th Auth0 aplication that we created above

Here’s how you can do this using AWS CDK:

 const auth0Provider = new iam.OpenIdConnectProvider(this, "Auth0Provider", {
      url: "https://YOUR_DOMAIN_NAME", // Replace with your Auth0 domain
      clientIds: [Client_Id],
    });
Enter fullscreen mode Exit fullscreen mode
  • The url is the Auth0 domain specific to your application.
  • The clientIds field should include the Client ID you retrieved from the Auth0 application settings. This creates an OIDC identity provider in AWS that trusts your Auth0 application.

Create a Cognito Identity Pool
Now, you need to create a Cognito Identity Pool that uses the Auth0 identity provider that we created above for authentication. This Identity Pool will issue AWS credentials to the users using which they will be able to access AWS Services(Kinesis in our case)

Here’s how to do it using AWS CDK:

 const identityPool = new cognito.CfnIdentityPool(this, "IdentityPool", {
      allowUnauthenticatedIdentities: false,
      identityPoolName: "MyAuth0IdentityPool",
      openIdConnectProviderArns: [auth0Provider.openIdConnectProviderArn],
    });
Enter fullscreen mode Exit fullscreen mode

Grant required role for AWS Service
To allow authenticated users to access AWS resources like Kinesis, you need to define an IAM role with the necessary permissions and attach it to the Identity Pool.

const authenticatedRole = new iam.Role(
      this,
      "CognitoKinesesAuthenticatedRole",
      {
        assumedBy: new iam.FederatedPrincipal(
          "cognito-identity.amazonaws.com",
          {
            StringEquals: {
              "cognito-identity.amazonaws.com:aud": identityPool.ref,
            },
            "ForAnyValue:StringLike": {
              "cognito-identity.amazonaws.com:amr": "authenticated",
            },
          },
          "sts:AssumeRoleWithWebIdentity"
        ),
        managedPolicies: [
          iam.ManagedPolicy.fromAwsManagedPolicyName("AmazonKinesisFullAccess"),
        ],
      }
    );

    // Attach the authenticated role to the identity pool
    new cognito.CfnIdentityPoolRoleAttachment(
      this,
      "IdentityPoolRoleAttachment",
      {
        identityPoolId: identityPool.ref,
        roles: {
          authenticated: authenticatedRole.roleArn,
        },
      }
    );
Enter fullscreen mode Exit fullscreen mode

UI Setup for Authentication and AWS Access

In this demo, we'll use a single index.html page to illustrate how to implement user authentication with Auth0 and access AWS resources securely.
To get started, include the necessary AWS and Auth0 SDKs in your index.html:

 <script src="https://sdk.amazonaws.com/js/aws-sdk-2.774.0.min.js"></script>
    <script src="https://cdn.auth0.com/js/auth0-spa-js/2.0/auth0-spa-js.production.js"></script>

Enter fullscreen mode Exit fullscreen mode

Configure Auth0
Create a configuration file named auth0.json with the following content. This file stores your Auth0 domain and client ID:

{
  "domain": "YOUR_DOMAIN",
  "clientId": "Client_Id"
}

Enter fullscreen mode Exit fullscreen mode

and then configure the auth0 client:

const response = await fetch("/auth0.json")
      const config = await response.json();

      auth0Client = await auth0.createAuth0Client({
        domain: config.domain,
        clientId: config.clientId,
        authorizationParams: {
          redirect_uri: window.location.origin,
        },
      });
Enter fullscreen mode Exit fullscreen mode

Retrieve AWS IAM Credentials
Upon successful login to AUth0, user will receive the Id token which can be used to obtain the IAM credentials from the cognito identity pool:

 AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: IDENTITY_POOL_ID,
        Logins: {
          [APP_DOMAIN_NAME]: idToken,
        },
      });

Enter fullscreen mode Exit fullscreen mode

By using this credentials, user would be able to securely call the kinesis stream

const kinesis = new AWS.Kinesis();
        const jsonString = JSON.stringify({ event: "linkClicked" });
        const kinesisParams = {
          Data: jsonString,
          PartitionKey: "key1",
          StreamName: "DemoKinesis",
        };

        kinesis.putRecord(kinesisParams, (err, data) => {
          if (err) console.error(err, err.stack);
          else console.log(data);
        });
Enter fullscreen mode Exit fullscreen mode

By following these steps, we can replace AWS Cognito User Pools with Auth0 for authentication while still leveraging Cognito Identity Pools to grant secure, temporary AWS credentials to theusers. This setup combines the flexibility of Auth0 with the power of AWS, enabling us to build secure, scalable applications with ease.

. .
Terabox Video Player