Amplify-js: Using Facebook Login, why does Amplify (using Auth.currentAuthenticatedUser()) not work immediately after login, but if I refresh the app (Command + R in the iOS simulator), the user is recognized?

Created on 6 Apr 2019  路  4Comments  路  Source: aws-amplify/amplify-js

* Which Category is your question related to? *
Amplify Facebook Login Integration

* What AWS Services are you utilizing? *
Amplify, Auth

* Provide additional details e.g. code snippets *

code is now working - here's the snippet

 import { 
   CognitoUser, 
   CognitoIdToken, 
   CognitoAccessToken, 
   CognitoRefreshToken, 
   CognitoUserSession, 
   CognitoUserPool } from 'amazon-cognito-identity-js';
 //import { withOAuth } from 'aws-amplify-react-native'
 const userPool = new CognitoUserPool({
   UserPoolId: config.aws_user_pools_id,
   ClientId: config.aws_user_pools_web_client_id,
 });

   import { AuthSession } from 'expo'
  // Open URL in a browser
  openURL = async (url) => {
      try {
        let result = await AuthSession.startAsync({ authUrl: url })
        this.getTokenbyCode(result.params.code)
      } catch(openURLError) {
        console.log(`openURLError: ${openURLError}`)
      }
    }

   getTokenbyCode = async (code) => {

      const details = {
        grant_type: 'authorization_code',
        code,
        client_id: userPool.clientId,
        redirect_uri: AuthSession.getRedirectUrl()
      }
      const formBody = Object.keys(details)
        .map(
          key => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`
        )
        .join("&");

     try {
        let res = await fetch(
        'https://DOMAIN.auth.us-west-2.amazoncognito.com/oauth2/token',
          {
            method: "POST",
            headers: {
              'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            body: formBody
          }
        )
        let tokenRequestJson = await res.json();
        const IdToken = new CognitoIdToken({ IdToken: tokenRequestJson.id_token });
        const AccessToken = new CognitoAccessToken({ AccessToken: tokenRequestJson.access_token });
        const RefreshToken = new CognitoRefreshToken({ RefreshToken: tokenRequestJson.refresh_token 
        })
          try {
            let userSession = new CognitoUserSession({ IdToken, AccessToken, RefreshToken });

            const userData = {
              Username: IdToken.payload['cognito:username'],
              Pool: userPool
            };
            let authUser = Auth.createCognitoUser(userData.Username); // THIS NOW WORKS
            let authSession = await Auth.userSession(authUser)
            let authCurrentUser = Auth.currentAuthenticatedUser()
          } catch (userError) {
         //HANDLE USERERROR
          }
      } catch (fetchError) {
         //HANDLE FETCHERROR
      }
Auth question

Most helpful comment

Thanks. I figured this out, and you should update your documentation.

this line is incorrect: let authUser = Auth.createCognitoUser(userData);
It should read this: let authUser = Auth.createCognitoUser(cognitoUser.getUsername());

Regarding your documentation, it is not at all straightforward. I tried it out and got an error saying that response.token is undefined.

Since my solution is working (I'm using Expo FWIW), I'm going to stick with the hack, unless you'd like to update your documentation to make it easier.

All 4 comments

@cmaronchick can you try this:

try {
            let userSession = new CognitoUserSession({ IdToken, AccessToken, RefreshToken });

            const userData = {
              Username: IdToken.payload['cognito:username'],
              Pool: userPool
            };
            let authUser = Auth.createCognitoUser(userData);

            authUser.setSession(userSession);

            let authSession = await Auth.userSession(authUser)
            let authCurrentUser = Auth.currentAuthenticatedUser();
 } catch (userError) {
         //HANDLE USERERROR
        }

By the way, the way you are using Amplify is kind of hacky and thus not recommended. Could you take a look at this about how to do federation in React-native?: https://aws-amplify.github.io/docs/js/authentication#oauth-and-federation-overview

Thanks. I figured this out, and you should update your documentation.

this line is incorrect: let authUser = Auth.createCognitoUser(userData);
It should read this: let authUser = Auth.createCognitoUser(cognitoUser.getUsername());

Regarding your documentation, it is not at all straightforward. I tried it out and got an error saying that response.token is undefined.

Since my solution is working (I'm using Expo FWIW), I'm going to stick with the hack, unless you'd like to update your documentation to make it easier.

@cmaronchick I've been really struggling with oauth amplify for expo as well. If it's not too much to ask can you please help me with your working code? I can't seem to get it work with Fb login or Google login :(

I've pretty much posted everything I used to get it working, but I added the updated code with the URL opener and all.

Was this page helpful?
0 / 5 - 0 ratings