Search code examples
javascriptreactjssingle-sign-onaws-amplifyaws-config

refereshToken is empty aws-amplify javascript


I use aws-amplify as shown below,

Amplify.configure({
  Auth: {
   
    region: config.aws.region,


    identityPoolRegion: config.aws.region,

    userPoolId: process.env.userPoolId,

    userPoolWebClientId: process.env.appClientId,


    oauth: {
      domain: process.env.domain,
      //  scope: ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin'],
      redirectSignIn: `${process.env.redirectSignIn}`,
      redirectSignOut: process.env.redirectSignout,
      responseType: code // NOTE: It was set to 'token' earlier and I used to get accessToken/IDToken back but refreshToken was empty
    }
  }
});

As you can see responseType was set to token and I was able to do microsoft SSO login successfully. I used to get AccessToken/IdToken in redirect URL but refreshtoken as always empty.

I want to generate refershToken to refresh session at later stage.

To get a refreshtoken, I saw I need to change responseType to code as shown above,

How I call to oauth2 endpoint (with responseType = code)

const azureLogin = () => {
    window.location.href = `https://${process.env.domain}/oauth2/authorize?identity_provider=${process.env.identityProviderName}&redirect_uri=${process.env.redirectSignIn}&response_type=${process.env.responseType}&client_id=${process.env.appClientId}&scope=aws.cognito.signin.user.admin+email+openid+phone+profile`;
  };

From my app, whenever I do (SSO) login it does following things,

browser's URL changes to something :

https://login.microsoftonline.com/62xxx-7x-4xxxf50-axx7-fxxx692/saml2?SAMLRequest=fZJbS8MwF********************

Then it changes to,

http://localhost:3000/auth/redirect?code=bccxxx-exx-4xx-8x-9xxxxxx

I get code but I don't what should I do with this code. how to use this code to get accessToken, IdToken and refreshToken?

Can someone pls help me with the flow?

PS: I checked AWS-amplify document also but flow is not clear. On top of it, there are no examples available which I can take help from.


Solution

  • after above setup, you start getting code.

    After getting code, you can get tokens by making a HTTP POST request as follow,

    const getToken= (code: string) => {
        const requestOptions = {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: new URLSearchParams({
            grant_type: 'authorization_code',
            code: `${code}`,
            client_id: `${process.env.appClientId}`,
            client_secret: `${process.env.secretHash}`,
            redirect_uri: `${process.env.redirectSignIn}`
          })
        };
    
        return fetch(`https://${process.env.domain}/oauth2/token`, requestOptions);
    
      }
    

    As response, you get all tokens successfully.