Amplify-js: Get `access_token`, `id_token` and `refresh_token` while using React Native Federated sign in method

Created on 13 Nov 2019  Â·  9Comments  Â·  Source: aws-amplify/amplify-js

* Which Category is your question related to? *
Auth

* What AWS Services are you utilizing? *
Cognito

* Provide additional details e.g. code snippets *

I want to get access_token, id_token and refresh_token while using React Native Federated sign in method. Below is my package.json:

{
  "name": "demoApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.6.2",
    "@react-native-community/cli-platform-android": "^2.9.0",
    "amazon-cognito-identity-js": "^3.2.0",
    "aws-amplify": "^1.2.4",
    "aws-amplify-react-native": "^2.2.3",
    "react": "16.9.0",
    "react-native": "0.61.4"
  }
}

Which method do I need to call using may be Auth class which can return me JWT tokens like access, refresh and idToken?

Auth pending-close-response-required question

All 9 comments

Calling await Auth.currenSession() will return the following object:

{ 
   "accessToken" :{},
   "clockDrift": 0,
   "idToken": {},
   "refreshToken": {}
}

I am getting CognitoIdentity object with a lot of details but no access
token or refresh token. Am I missing something?

On Wed, Nov 13, 2019, 21:06 Ivan Artemiev notifications@github.com wrote:

Calling await Auth.currenSession() will return the following object:

{
"accessToken" :{},
"clockDrift": 0,
"idToken": {},
"refreshToken": {}
}

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/aws-amplify/amplify-js/issues/4391?email_source=notifications&email_token=AJ5ONHIC2ECCFJQJPIWZEYTQTQNGXA5CNFSM4JM4EXU2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOED6RJAI#issuecomment-553456769,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AJ5ONHMVJEAOZQPMRFJS4P3QTQNGXANCNFSM4JM4EXUQ
.

Please provide a code sample of your App.js and describe what steps you're taking to add Federated Sign-In. Did you add authentication through the Amplify CLI? Or are you attempting to use an existing Cognito User Pool?

I am using an existing Cognito User Pool. I have used
Auth.federatedSignIn() method for Facebook provider in React Native
0.61.x.

My AWS configuration are set as well. I am able to get CognitoIdentity
credentials and Facebook access tokens, therefore O am assuming that
Cognity knows my user and allows to login.

But somehow I dont have access, refresh and idToken which are needed. I
will post my package.json, and app code soon here.

On Wed, Nov 13, 2019, 21:20 Ivan Artemiev notifications@github.com wrote:

Please provide a code sample of your App.js and describe what steps you're
taking to add Federated Sign-In. Did you add authentication through the
Amplify CLI? Or are you attempting to use an existing Cognito User Pool?

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/aws-amplify/amplify-js/issues/4391?email_source=notifications&email_token=AJ5ONHONS5RN4W7OJ5VWFRDQTQO2RA5CNFSM4JM4EXU2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOED6S2CA#issuecomment-553463048,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AJ5ONHLDIIP5U6LKO26K7ZDQTQO2RANCNFSM4JM4EXUQ
.

Hi @iartemiev -

My package.json looks like below:

{
  "name": "demoapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.6.2",
    "@react-native-community/cli-platform-android": "^2.9.0",
    "amazon-cognito-identity-js": "^3.2.0",
    "aws-amplify": "^1.2.4",
    "aws-amplify-react-native": "^2.2.3",
    "axios": "^0.19.0",
    "i18n-js": "^3.3.0",
    "metro-config": "^0.56.3",
    "moment": "^2.24.0",
    "native-base": "^2.13.7",
    "prop-types": "^15.7.2",
    "react": "16.9.0",
    "react-native": "0.61.4",
    "react-native-animatable": "^1.3.2",
    "react-native-app-intro-slider": "^3.0.0",
    "react-native-background-geolocation": "^3.3.0",
    "react-native-device-info": "^5.2.1",
    "react-native-easy-toast": "^1.2.0",
    "react-native-elements": "^1.2.0",
    "react-native-fbsdk": "^1.1.0",
    "react-native-gesture-handler": "^1.4.1",
    "react-native-image-picker": "^1.1.0",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-localize": "^1.3.0",
    "react-native-permissions": "^2.0.2",
    "react-native-picker-select": "^6.3.3",
    "react-native-reanimated": "^1.2.0",
    "react-native-splash-screen": "^3.2.0",
    "react-native-svg": "^9.13.2",
    "react-native-svg-transformer": "^0.13.0",
    "react-native-svg-uri": "^1.2.3",
    "react-native-vector-icons": "^6.6.0",
    "react-navigation": "^4.0.2",
    "react-navigation-animated-switch": "^0.3.1",
    "react-navigation-drawer": "^2.1.1",
    "react-navigation-stack": "^1.5.4",
    "react-navigation-tabs": "^2.5.3",
    "react-redux": "^7.1.1",
    "redux": "^4.0.4",
    "redux-devtools-extension": "^2.13.8",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.0.5",
    "reduxsauce": "^1.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.7.2",
    "@babel/runtime": "^7.7.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.6.0",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.57.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

My app.js looks like below:

import React, { useEffect, useState, useContext } from 'react';
import { LoginManager, AccessToken  } from "react-native-fbsdk";
import { Authenticator, SignIn, SignUp, ConfirmSignUp } from 'aws-amplify-react-native';
import Amplify, { I18n, Auth, Hub } from 'aws-amplify';
import awsconfig from './aws-exports';
import { Text, View, Button, Linking } from 'react-native';
import ExampleScreen from './App/Containers/Example/ExampleScreen'

Amplify.configure(awsconfig);

const FBLogin = (props) => {

  function handleChange(credentials) {
    props.onChange(credentials);
  }  

    function facebookLogin() {
      const authDetails = {};
      LoginManager.logInWithPermissions(["public_profile", "email"]).then(
        function(result) {
          console.log("Facebook result: ", result);
          if (result.isCancelled) {
          } else {
            AccessToken.getCurrentAccessToken().then(
              (data) => {

                const accessToken = data.accessToken;
                const responseInfoCallback = async(error, result) => {
                  if (error) {
                    console.log(error);
                    console.log('Error fetching data=', error);
                  } else {
                    authDetails.provider = "facebook";
                    authDetails.userMeta = result;
                    console.log('Success fetching data: ', result);
                  }
                };

                Auth.federatedSignIn('facebook', {'token': data.accessToken, 'expires_at': data.dataAccessExpirationTime}).then(credentials => {

                  authDetails.credentials = credentials;
                  console.log("AWS Login through Facebook successful. Creds: ", credentials);                            handleChange(authDetails);

                }).catch(e=>{
                  console.log("AWS Login through Facebook failed: ", e);
                });
              }
            );
          }
        },function(error) {
          console.log("Login fail with error: " + error);
        }
      );
    }

  return (
      <View>      
        <Button title="facebbok Login" onPress={() => facebookLogin()} />
      </View>
     );
}


function App() {
    const [appWideAuthUser, setappWideAuthUser] = useState({"credentials": ""});

    return (
      <Authenticator hideDefault={true}  >
          <FBLogin value={appWideAuthUser} onChange={handleChange} />
        </Authenticator>
    );

}

export default App;

So once Auth.federatedSignIn() is triggered, I am able to get the CognitoIdentity token but I can not get refresh, access and id tokens.

Thanks for posting the code sample, @Ravim-addweb.

The way you’re utilizing Auth.federatedSignIn here (passing in the accessToken from Facebook) interacts solely with the Identity Pool and is only supposed to retrieve a CognitoIdentityCredential from your Cognito Identity Pool, so what you’re experiencing is consistent with the expected behavior (as described here: https://aws-amplify.github.io/docs/js/authentication#identity-pool-federation)

If you want to utilize OAuth through Cognito User Pools and retrieve access, refresh, and id tokens from Cognito you would need to use the OAuth/HostedUI flow: https://aws-amplify.github.io/docs/js/authentication#oauth-and-federation-overview

If you don’t want to do that and prefer to keep using Identity Pools, Amplify has limited capacity to handle refresh. See: https://aws-amplify.github.io/docs/js/authentication#token-refresh

Ivan, thank you so much for providing all the information.

Yes I realized couple of hours back that I will have to shift to Hosted UI
solution.

I really wish there was an easy way to get tokens without opening the
browser.

On Thu, Nov 14, 2019, 03:00 Ivan Artemiev notifications@github.com wrote:

Thanks for posting the code sample, @Ravim-addweb
https://github.com/Ravim-addweb.

The way you’re utilizing Auth.federatedSignIn here (passing in the
accessToken from Facebook) interacts solely with the Identity Pool and is
only supposed to retrieve a CognitoIdentityCredential from your Cognito
Identity Pool, so what you’re experiencing is consistent with the expected
behavior (as described here:
https://aws-amplify.github.io/docs/js/authentication#identity-pool-federation
)

If you want to utilize OAuth through Cognito User Pools and retrieve
access, refresh, and id tokens from Cognito you would need to use the
OAuth/HostedUI flow:
https://aws-amplify.github.io/docs/js/authentication#oauth-and-federation-overview

If you don’t want to do that and prefer to keep using Identity Pools,
Amplify has limited capacity to handle refresh. See:
https://aws-amplify.github.io/docs/js/authentication#token-refresh

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/aws-amplify/amplify-js/issues/4391?email_source=notifications&email_token=AJ5ONHO72ZBNAKL6TAK7C33QTRWV3A5CNFSM4JM4EXU2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOED7XGYQ#issuecomment-553612130,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AJ5ONHJ3BRRCEIKJ5KVHRH3QTRWV3ANCNFSM4JM4EXUQ
.

Happy to help! Thank you for your feedback

Thanks @iartemiev - after reading this in depth it becomes crystal clear that with React Native Federated sign in works to get Federated Identity only and not User Pool Identity.

I really wish these guys can enrich the documentation :(

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lucasmike picture lucasmike  Â·  3Comments

guanzo picture guanzo  Â·  3Comments

oste picture oste  Â·  3Comments

benevolentprof picture benevolentprof  Â·  3Comments

romainquellec picture romainquellec  Â·  3Comments