How to use Auth0 with Amplify react web app?

0

Hello, I am working on a react app using Amplify where I want to use Auth0 to authenticate users and grant access to Amplify resources such as a graphql API (AppSync).

The Auth0 quick start (https://auth0.com/docs/quickstart/spa/react/interactive) got me to the point of adding login, logout, and user profile to the app, BUT this doesn't help me integrate with Amplify. Through the AppSync console, I set my AppSync default authorization mode to OpenID Connect and then set the provider to my Auth0 domain / issuer URL. Then when my graphql schema uses the @aws_oidc and @auth(rules: [{ allow: private, provider: oidc }]) rules and can successfully run queries through the console with an auth token pasted in.

But how can I call API.graphql with that auth token? The following is not working, with error Error: No current user. Seems like I should be using amplify's Auth in here instead.

      const { user, isLoading, getAccessTokenSilently } = useAuth0();
      const token = await getAccessTokenSilently();
      const response = await API.graphql<GraphQLQuery<MyMutation>>({
        query: updateCredit,
        variables: { input: credit },
        authMode: GRAPHQL_AUTH_MODE.OPENID_CONNECT,
        authToken: token,
      });
  • Update:

I've made some progress but gotten stuck yet again. This medium article was great at explaining how the flow should work: https://tomoima525.medium.com/aws-cognito-authentication-using-auth0-as-openid-connect-provider-4db2a03f9a31

And a doc explaining how to set up an identity pool with role that has the right trust policy: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_oidc.html

However nothing I've tried resolves this error: InvalidIdentityPoolConfigurationException: Invalid identity pool configuration. Check assigned IAM roles for this pool.

I have checked this trust relationship for the role many times:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "cognito-identity.amazonaws.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "cognito-identity.amazonaws.com:aud": "us-east-1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                },
                "ForAnyValue:StringLike": {
                    "cognito-identity.amazonaws.com:amr": "authenticated"
                }
            }
        }
    ]
}
1 Answer
0
Accepted Answer

Well, it turns out I was close and in my Cognito identity pool I could see the identity created when signing in with Auth0 and then passing the ID token with Amplify's Credentials.set method:

import { useAuth0 } from '@auth0/auth0-react';
import { Auth } from 'aws-amplify';
import { Credentials } from '@aws-amplify/core';
....

const { isAuthenticated, loginWithRedirect, getIdTokenClaims } = useAuth0();
const config = getConfig();
useEffect(() => {
    const fetchAccessToken = async () => {
      const idtoken = await getIdTokenClaims();
      await Credentials.set(
        {
          provider: config.domain,
          token: idtoken.__raw,
          user: { name: idtoken.email },
          expires_at: idtoken.exp,
        },
        'federation'
      );

      const currentUser = await Auth.currentAuthenticatedUser();
      console.log('currentUser: ', currentUser);
    };
    if (isAuthenticated) {
      fetchAccessToken();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated]);

For some reason when setting up the Auth0 provider for my Cognito identity pool, I had chosen to use default mappings in the 'Attributes for access control' section. After changing this setting to Inactive, the InvalidIdentityPoolConfigurationException goes away!

answered 7 months ago
profile picture
EXPERT
reviewed 11 days ago
  • Still be careful in using id token as authentication mechanism

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions