Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auth.federatedSignIn with Google calling /token endpoint twice #6330

Closed
reggiepangilinan opened this issue Jul 15, 2020 · 28 comments
Closed
Assignees
Labels
Auth Related to Auth components/category bug Something isn't working

Comments

@reggiepangilinan
Copy link

reggiepangilinan commented Jul 15, 2020

Describe the bug
A clear and concise description of what the bug is.

I have a react app that is using a custom login page. Which calls Google for federated signin.
When I try to login using Google. The behaviour of Auth.federatedSignIn is unpredictable.
Sometimes it succeeds sometimes it fails

I checked all of these but it did not fix my issue
#3642
#3185 (comment)
#6041
#5829
#6172

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...' Sign-in page
  2. Click on '....' Open with google
  3. See error

Expected behavior
A clear and concise description of what you expected to happen.

I was hoping after the federated signin using

                const result = await Auth.federatedSignIn({
                  provider: CognitoHostedUIIdentityProvider.Google,
                });

I can just set my currentUser in my global context

      const userInfo = await Auth.currentUserInfo();
      if (userInfo) {
        const currentUser: CurrentUser = initializeCurrentUser(userInfo);
        setCurrentUser(currentUser);
      }

Code Snippet
Please provide a code snippet or a link to sample code of the issue you are experiencing to help us reproduce the issue. (Be sure to remove any sensitive data)

This basically how is signin using google

              try {
                const result = await Auth.federatedSignIn({
                  provider: CognitoHostedUIIdentityProvider.Google,
                });
                console.log(result);
                alert('user logged in via google');
              } catch (err) {
                console.log(err);
              }

Screenshots
If applicable, add screenshots to help explain your problem.
Checkout this screenshot

image

What is Configured?
If applicable, please provide what is configured for Amplify CLI:

  • Which steps did you follow via Amplify CLI when configuring your resources.
  • I just added an auth project using amplify add auth
  • Configure it to connect my google app
  • Which resources do you have configured?
    • If applicable, please provide your aws-exports file:

const awsmobile = {
"aws_project_region": "ap-southeast-2",
"aws_cognito_identity_pool_id": "ap-southeast-2:9f419afd-8e58-42e0-a5be-2f6ae54ef525",
"aws_cognito_region": "ap-southeast-2",
"aws_user_pools_id": "ap-southeast-2_MTlyh2uhv",
"aws_user_pools_web_client_id": "4vhitjj2i7egv4v44nohgpedb0",
"oauth": {
"domain": "mycirclesbc57058d-bc57058d-dev.auth.ap-southeast-2.amazoncognito.com",
"scope": [
"phone",
"email",
"openid",
"profile",
"aws.cognito.signin.user.admin"
],
"redirectSignIn": "http://localhost:3031/",
"redirectSignOut": "http://localhost:3031/",
"responseType": "code"
},
"federationTarget": "COGNITO_USER_POOLS"
};


export default awsmobile;
  • If applicable, please provide your manual configuration example:
{
 Auth: {
     identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',
     region: 'XX-XXXX-X',
     identityPoolRegion: 'XX-XXXX-X',
     userPoolId: 'XX-XXXX-X_abcd1234',
     userPoolWebClientId: 'a1b2c3d4e5f6g7h8i9j0k1l2m3',
     mandatorySignIn: false,
     authenticationFlowType: 'USER_PASSWORD_AUTH',
     oauth: {
         domain: 'your_cognito_domain',
         scope: ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin'],
         redirectSignIn: 'http://localhost:3000/',
         redirectSignOut: 'http://localhost:3000/',
         responseType: 'code' // or 'token', note that REFRESH token will only be generated when the responseType is code
        }
    }
}
  • If applicable, provide more configuration data, for example for Amazon Cognito, run aws cognito-idp describe-user-pool --user-pool-id us-west-2_xxxxxx (Be sure to remove any sensitive data)
Environment
npx envinfo --system --binaries --browsers --npmPackages --npmGlobalPackages

System:
OS: macOS 10.15.5
CPU: (8) x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
Memory: 691.59 MB / 16.00 GB
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 10.15.3 - /usr/local/bin/node
Yarn: 1.13.0 - /usr/local/bin/yarn
npm: 6.14.6 - ~/dev/mycircles/node_modules/.bin/npm
Watchman: 4.7.0 - /usr/local/bin/watchman
Browsers:
Chrome: 83.0.4103.116
Safari: 13.1.1
npmPackages:
@aws-amplify/ui-react: ^0.2.10 => 0.2.10
@storybook/addon-actions: ^5.3.19 => 5.3.19
@storybook/addon-links: ^5.3.19 => 5.3.19
@storybook/addons: ^5.3.19 => 5.3.19
@storybook/preset-create-react-app: ^3.1.3 => 3.1.3
@storybook/react: ^5.3.19 => 5.3.19
@storybook/theming: ^5.3.19 => 5.3.19
@testing-library/jest-dom: ^4.2.4 => 4.2.4
@testing-library/react: ^9.3.2 => 9.5.0
@testing-library/user-event: ^7.1.2 => 7.2.1
@types/jest: ^24.0.0 => 24.9.1
@types/node: ^12.0.0 => 12.12.48
@types/react: ^16.9.0 => 16.9.41
@types/react-dom: ^16.9.0 => 16.9.8
@types/react-router-dom: ^5.1.5 => 5.1.5
@types/yup: ^0.29.3 => 0.29.3
@typescript-eslint/eslint-plugin: ^3.6.0 => 3.6.0
@typescript-eslint/parser: ^3.6.0 => 3.6.0
aws-amplify: ^3.0.20 => 3.0.20
eslint-config-prettier: ^6.11.0 => 6.11.0
eslint-config-react: ^1.1.7 => 1.1.7
eslint-plugin-prettier: ^3.1.4 => 3.1.4
formik: ^2.1.4 => 2.1.4
import-sort-style-module: ^6.0.0 => 6.0.0
install: ^0.13.0 => 0.13.0
node-sass: ^4.14.1 => 4.14.1
npm: ^6.14.6 => 6.14.6
plop: ^2.7.1 => 2.7.1
prettier: ^2.0.5 => 2.0.5
prettier-plugin-import-sort: 0.0.4 => 0.0.4
react: ^16.13.1 => 16.13.1
react-dom: ^16.13.1 => 16.13.1
react-icons: ^3.10.0 => 3.10.0
react-router-dom: ^5.2.0 => 5.2.0
react-scripts: 3.4.1 => 3.4.1
react-use: ^15.3.2 => 15.3.2
typescript: ~3.7.2 => 3.7.5
yup: ^0.29.1 => 0.29.1
npmGlobalPackages:
@angular/cli: 1.7.3
@aws-amplify/cli: 4.24.1
angular-cli-ghpages: 0.5.2
babel-cli: 6.11.4
babel-eslint: 6.1.2
bower: 1.7.9
create-react-library: 2.6.7
create-react-native-app: 1.0.0
eslint-plugin-meteor: 4.0.0
eslint-plugin-react: 6.0.0
eslint: 3.2.2
exp: 49.0.1
gatsby-cli: 2.11.5
generator-hottowel: 0.4.1
generator-rn-toolbox: 2.0.10
gulp: 3.9.1
ignite-cli: 2.0.0-beta.8
mantra-cli: 0.4.0-rc.4
mocha: 3.0.1
modus-ui: 0.0.15
nodemon: 1.9.2
npm: 6.4.1
react-native-cli: 2.0.1
swagger: 0.7.5
tsd: 0.6.5
typescript: 1.8.10
typings: 1.3.0
yo: 1.8.5

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari] Chrome
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

You can turn on the debug mode to provide more info for us by setting window.LOG_LEVEL = 'DEBUG'; in your app.

log.js:24 [HMR] Waiting for update signal from WDS...
ConsoleLogger.ts:91 [DEBUG] 40:19.247 AuthClass - OAuth signIn in progress, waiting for resolution...
OAuth.ts:166 POST https://mycirclesbc57058d-bc57058d-dev.auth.ap-southeast-2.amazoncognito.com/oauth2/token 400
index.js:1 [ERROR] 40:19.699 OAuth - Error handling auth response. Error: invalid_request
    at OAuth.<anonymous> (OAuth.ts:175)
    at step (OAuth.ts:1)
    at Object.next (OAuth.ts:1)
    at fulfilled (OAuth.ts:1)
ConsoleLogger.ts:99 [DEBUG] 40:19.701 AuthClass - Error in cognito hosted auth response Error: invalid_request
    at OAuth.<anonymous> (OAuth.ts:175)
    at step (OAuth.ts:1)
    at Object.next (OAuth.ts:1)
    at fulfilled (OAuth.ts:1)
ConsoleLogger.ts:99 [DEBUG] 40:19.702 Hub - Dispatching to auth with  
{event: "signIn_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "The OAuth response flow failed"}
ConsoleLogger.ts:99 [DEBUG] 40:19.702 Hub - Dispatching to auth with  
{event: "signIn_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "The OAuth response flow failed"}
ConsoleLogger.ts:99 [DEBUG] 40:19.703 AnalyticsClass - on hub capsule auth 
{event: "signIn_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "The OAuth response flow failed"}
ConsoleLogger.ts:99 [DEBUG] 40:19.704 Hub - Dispatching to auth with  
{event: "signIn_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "The OAuth response flow failed"}
ConsoleLogger.ts:99 [DEBUG] 40:19.704 Hub - Dispatching to auth with  
{event: "signIn_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "The OAuth response flow failed"}
index.js:1 [ERROR] 40:19.706 My-Logger - user sign in failed
ConsoleLogger.ts:99 [DEBUG] 40:19.706 Hub - Dispatching to auth with  
{event: "signIn_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "The OAuth response flow failed"}
ConsoleLogger.ts:99 [DEBUG] 40:19.706 Hub - Dispatching to auth with  
{event: "cognitoHostedUI_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning to the Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:19.707 Hub - Dispatching to auth with  
{event: "cognitoHostedUI_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning to the Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:19.707 AnalyticsClass - on hub capsule auth 
{event: "cognitoHostedUI_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning to the Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:19.707 Hub - Dispatching to auth with  
{event: "cognitoHostedUI_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning to the Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:19.708 Hub - Dispatching to auth with  
{event: "cognitoHostedUI_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning to the Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:19.708 Hub - Dispatching to auth with  
{event: "cognitoHostedUI_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning to the Cognito Hosted UI"}
ConsoleLogger.ts:91 [DEBUG] 40:19.708 AuthClass - OAuth signIn resolved: cognitoHostedUI_failure
ConsoleLogger.ts:99 [DEBUG] 40:19.709 Hub - Dispatching to auth with  
{event: "customState_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning state"}
ConsoleLogger.ts:99 [DEBUG] 40:19.709 Hub - Dispatching to auth with  
{event: "customState_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning state"}
ConsoleLogger.ts:99 [DEBUG] 40:19.710 AnalyticsClass - on hub capsule auth 
{event: "customState_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning state"}
ConsoleLogger.ts:99 [DEBUG] 40:19.710 Hub - Dispatching to auth with  
{event: "customState_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning state"}
ConsoleLogger.ts:99 [DEBUG] 40:19.711 Hub - Dispatching to auth with  
{event: "customState_failure", data: Error: invalid_request
    at OAuth.<anonymous> (http://localhost:3031/static/js/25.chunk.js:14402:…, message: "A failure occurred when returning state"}
ConsoleLogger.ts:91 [DEBUG] 40:19.712 AuthClass - Failed to get user from user pool
ConsoleLogger.ts:91 [DEBUG] 40:19.712 AuthClass - No current user
ConsoleLogger.ts:91 [DEBUG] 40:19.758 Credentials - set credentials from session
ConsoleLogger.ts:99 [DEBUG] 40:20.17 Credentials - Load credentials successfully 
{accessKeyId: "ASIAWJKZP25X7REMRMOZ", secretAccessKey: "7T4GMa6ljSgZQjQXBpzaqq4BbRPgZqu0IlkpnUFW", sessionToken: "IQoJb3JpZ2luX2VjEPf//////////wEaDmFwLXNvdXRoZWFzdC…UcjEklulURxuXi3REjUZbI1Hlhh/Ry4eiv/Ll48JyBt6bgyw=", expiration: Wed Jul 15 2020 17:40:19 GMT+1000 (Australian Eastern Standard Time)}
ConsoleLogger.ts:99 [DEBUG] 40:20.17 AuthClass - AWS credentials 
{accessKeyId: "ASIAWJKZP25X7REMRMOZ", secretAccessKey: "7T4GMa6ljSgZQjQXBpzaqq4BbRPgZqu0IlkpnUFW", sessionToken: "IQoJb3JpZ2luX2VjEPf//////////wEaDmFwLXNvdXRoZWFzdC…UcjEklulURxuXi3REjUZbI1Hlhh/Ry4eiv/Ll48JyBt6bgyw=", expiration: Wed Jul 15 2020 17:40:19 GMT+1000 (Australian Eastern Standard Time), identityId: "ap-southeast-2:be37f777-6ac8-43f6-8d1d-d941bde45258", …}
ConsoleLogger.ts:99 [DEBUG] 40:20.19 Hub - Dispatching to auth with  
{event: "signIn", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in"}
ConsoleLogger.ts:99 [DEBUG] 40:20.19 Hub - Dispatching to auth with  
{event: "signIn", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in"}
ConsoleLogger.ts:99 [DEBUG] 40:20.20 AnalyticsClass - on hub capsule auth 
{event: "signIn", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in"}
ConsoleLogger.ts:99 [DEBUG] 40:20.20 Hub - Dispatching to auth with  
{event: "signIn", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in"}
ConsoleLogger.ts:99 [DEBUG] 40:20.20 Hub - Dispatching to auth with  
{event: "signIn", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in"}
index.js:1 [ERROR] 40:20.21 My-Logger - user signed in
ConsoleLogger.ts:99 [DEBUG] 40:20.21 Hub - Dispatching to auth with  
{event: "cognitoHostedUI", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in via Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:20.21 Hub - Dispatching to auth with  
{event: "cognitoHostedUI", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in via Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:20.21 AnalyticsClass - on hub capsule auth 
{event: "cognitoHostedUI", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in via Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:20.22 Hub - Dispatching to auth with  
{event: "cognitoHostedUI", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in via Cognito Hosted UI"}
ConsoleLogger.ts:99 [DEBUG] 40:20.22 Hub - Dispatching to auth with  
{event: "cognitoHostedUI", data: CognitoUser, message: "A user Google_109420508002754882006 has been signed in via Cognito Hosted UI"}
@reggiepangilinan reggiepangilinan added the to-be-reproduced Used in order for Amplify to reproduce said issue label Jul 15, 2020
@reggiepangilinan reggiepangilinan changed the title Auth.federatedSignIn calling /token endpoint twice Auth.federatedSignIn with Google calling /token endpoint twice Jul 15, 2020
@amhinson amhinson added the Auth Related to Auth components/category label Jul 15, 2020
@seanbecker15
Copy link

I am experiencing the same issue with Google federated sign in.

@harrysolovay
Copy link
Contributor

Some thoughts.

It seems you have two redirect signins/signouts, http://localhost:3000/ and http://localhost:3001. Which of these do you have configured in for Cognito vs. the GCP OAuth app? Are they both correct?

I want to confirm that you're calling Amplify.configure(awsExports) at the program's root, and that you've imported the CognitoHostedUIIdentityProvider enum from @aws-amplify/auth.

Lastly, can you (A) go to the AWS Cognito User Pool (in the AWS Console), remove the user that you're trying to log in, and do the same for the GCP OAuth app (in the GCP console)? Then try yet another log in.

If none of the above works, please let us know.

@reggiepangilinan
Copy link
Author

Some thoughts.

It seems you have two redirect signins/signouts, http://localhost:3000/ and http://localhost:3001. Which of these do you have configured in for Cognito vs. the GCP OAuth app? Are they both correct?

I want to confirm that you're calling Amplify.configure(awsExports) at the program's root, and that you've imported the CognitoHostedUIIdentityProvider enum from @aws-amplify/auth.

Lastly, can you (A) go to the AWS Cognito User Pool (in the AWS Console), remove the user that you're trying to log in, and do the same for the GCP OAuth app (in the GCP console)? Then try yet another log in.

If none of the above works, please let us know.

Hey @harrysolovay thanks for the suggestion. Unfortunately it did not work.
I just have one url and basically created a new google account to try and login and I’m still getting the same issue.

Cheers

@seanbecker15
Copy link

seanbecker15 commented Aug 4, 2020

@harrysolovay I noticed the same console error but it is actually not causing any tangible problems for me other than a duplicate request and console error.

I am running a React project and calling Amplify.configure in App.ts (first child of root).

Let me know if any other details I can provide to help.

Edit: I realized that this might not be clear. When I call Auth.federatedSignIn I see two requests: one fails and the other one succeeds.

@harrysolovay
Copy link
Contributor

@seanbecker15 are you certain it's a duplicate and not just a second request? The OAuth flow involves exchanging the 3rd party tokens for that of AWS, so that you can make direct service calls from the browser. Are the requests identical?

@elorzafe
Copy link
Contributor

elorzafe commented Aug 7, 2020

@reggiepangilinan You wont be able to await Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google }) because that will redirect the app.

@seanbecker15 can you trying cleaning your modules and install the library latest

@reggiepangilinan
Copy link
Author

@elorzafe yeah, I updated that part of the code. I just redirect to the callback page.
I can still see two requests though.

One is
POST /oauth2/token
grant_type=authorization_code&code=XXXXX-a992-4bfd-b6bb-3cd9960061dc&client_id=2f5eh1fiv79m2bljjdqmv02q3t&redirect_uri=http%3A%2F%2Flocalhost%3A3031%2Fsign-up-callback%2F&code_verifier=LnHoSqYAwgue01nBv45XXTdGQVDMr81OS0dTsHgtLxcrBZ3D8R1uSPYbeNrSoYZUuso67TvIMJ4WSpbWCd9NphlNj1kpYAGWe6fByxtkDtyBsTXH4FFpNCoA1gbcZO66

Returns 200

And the other one is
POST /oauth2/token
grant_type=authorization_code&code=XXXXX-a992-4bfd-b6bb-3cd9960061dc&client_id=2f5eh1fiv79m2bljjdqmv02q3t&redirect_uri=http%3A%2F%2Flocalhost%3A3031%2Fsign-up-callback%2F

Returns 400

@ericclemmons
Copy link
Contributor

As I was testing out #6146 I experienced the same problem after signing in with Google:

Screen Shot 2020-08-26 at 10 42 01 AM
Screen Shot 2020-08-26 at 10 42 10 AM

The second calls is missing code_verifier as a param, but has the same code and client_id, so it's likely a bug.

Removing to-be-reproduced...

@ericclemmons ericclemmons removed the to-be-reproduced Used in order for Amplify to reproduce said issue label Aug 26, 2020
@Alk3m1st
Copy link

Alk3m1st commented Sep 2, 2020

Also experiencing this when using Auth.federatedSignIn({provider: 'Google'}) unfortunately.

@slatemates
Copy link

Exactly same issue when trying to sign in using google federated SignIN

@vidhyasagarj
Copy link

Stuck with the same issue. Any Idea on the root cause?

@ericclemmons
Copy link
Contributor

For clarification, did the sign in flow work at least? As in, even though a 2nd call happened with an error in the console, was the user at least signed in correctly?

(It was in my testing, but want to confirm if this is breaking or not)

@slatemates
Copy link

slatemates commented Sep 12, 2020 via email

@sammartinez sammartinez added the to-be-reproduced Used in order for Amplify to reproduce said issue label Sep 16, 2020
@twvik
Copy link

twvik commented Sep 21, 2020

Seeing the same issue. There are two requests to oauth2/token on custom domain and 2nd POST request doesn't have code_verifier.

@elorzafe
Copy link
Contributor

@twvik @vidhyasagarj @Alk3m1st @reggiepangilinan @seanbecker15

I am only seeing one request, this are the steps I went thru.

  1. I created a react app using CRA (used typescript template npx create-react-app my-app --template typescript
  2. Created an amplify project using amplify-cli
  3. On my amplify project added Auth following Social sign in (OAuth) guide
  4. App.tsx code
import React from 'react';
import './App.css';
import { Amplify } from '@aws-amplify/core';
import { Auth, CognitoHostedUIIdentityProvider } from '@aws-amplify/auth';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);

 function App() {
  React.useEffect(() => {
    (async () => {
      const userInfo = await Auth.currentUserInfo();
      console.log({userInfo});
    })();
  })
 
  function hostedUISignIn() {
    Auth.federatedSignIn({provider: CognitoHostedUIIdentityProvider.Google});
  }

  return (
    <div className="App">
      <header className="App-header">
        <button onClick={hostedUISignIn}>sign in with hosted ui</button>
      </header>
    </div>
  );
}

export default App;
  1. My aws-exports.js file looks like this
const awsmobile = {
    "aws_project_region": "us-west-2",
    "aws_cognito_identity_pool_id": "us-west-2:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
    "aws_cognito_region": "us-west-2",
    "aws_user_pools_id": "us-west-2_xxxxxxxx",
    "aws_user_pools_web_client_id": "xxxxxxxxxx",
    "oauth": {
        "domain": "xxxxxxxxxxx-xxxxxxxxxx-dev.auth.us-west-2.amazoncognito.com",
        "scope": [
            "phone",
            "email",
            "openid",
            "profile",
            "aws.cognito.signin.user.admin"
        ],
        "redirectSignIn": "http://localhost:3000/",
        "redirectSignOut": "http://localhost:3000/",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS"
};


export default awsmobile;

This are the request after clicking sign in with hosted ui
image

@dyson-yamashita
Copy link

I have same problem.
@elorzafe Could you tell me the versions of aws-amplify/core and aws-amplify/auth?

@enzoames
Copy link

enzoames commented Oct 3, 2020

I can confirm I am experiencing the same issue... @ericclemmons thanks for the great work you've been doing. I have been following it from the sidelines!

Using Next.js

_app.js

Amplify.configure(amplifyConfig);

function MyApp({ Component, pageProps }) {
  ...
  useEffect(() => {
    dispatch(getCurrentUser()); // simply a redux action which does: const { Auth } = withSSRContext(); const res = await Auth.currentAuthenticatedUser(); 

    Hub.listen('auth', ({ payload: { event, data } }) => {
      switch (event) {
        case 'signIn': {
          console.log('APP::Hub::Login', data);
          break;
        }
        case 'signOut':
          console.log('APP::Hub::SignOut', data);
          break;
        default:
          break;
      }
    });
  }, []);

amplifyConfig.js

export default {
  Auth: {
    region: 'eu-east-1',
    userPoolId: process.env.USER_POOL_ID,
    userPoolWebClientId: process.env.USER_POOL_CLIENT_ID,
    mandatorySignIn: true,
    cookieStorage: {
      domain: 'http://localhost:3000/',
      path: '/',
      expires: 120,
      secure: 'false',
    },
    oauth: {
      domain: 'xxxx-xxxx.auth.us-east-1.amazoncognito.com',
      scope: ['email', 'profile', 'phone', 'openid'],
      redirectSignIn: 'http://localhost:3000/profile',
      redirectSignOut: 'http://localhost:3000/,
      responseType: 'code',
    },
    federationTarget: 'COGNITO_USER_POOLS',
  },
  ssr: true,
};

when user clicks Continue with Facebook, the following redux action gets triggered

export const continueWithFacebook = () => async dispatch => {
  try {
    dispatch({ type: CONTINUE_WITH_REQUEST });
    const { Auth } = withSSRContext();
    Auth.federatedSignIn({ provider: 'Facebook' });
  } catch (err) {
    dispatch({ type: CONTINUE_WITH_FAILURE, payload: { error: err } });
  }
};

I do see the first request being successful

Screen Shot 2020-10-03 at 6 17 02 PM

and the next one request simply returning { error: "invalid_grant" }

from the console I can see that the Hub Listener detects the user singing in

Screen Shot 2020-10-03 at 6 26 28 PM

Cookie storage I see
Screen Shot 2020-10-03 at 7 28 57 PM

Refreshing the page removes everything under the cookie storage and the user is not persistent.

Any pointers would be really helpful, or if anyone has found a workaround, that would also help. Maybe I can move on to different parts of my app and circle back to this once there is a solution...

Thanks!

@emmanueloui
Copy link

emmanueloui commented Oct 15, 2020

Hi,
exactly the same problem here with a very simple app.
My cognito is setup with a saml idp, and when user come back to the app, there is 2 call of /token with error 400 on the second.

image

@sammartinez sammartinez added bug Something isn't working and removed to-be-reproduced Used in order for Amplify to reproduce said issue labels Oct 15, 2020
@VM1801
Copy link

VM1801 commented Oct 27, 2020

Guys do we have any updates on this ? Experiencing same troubles with Angular application

@thebabyjay
Copy link

I was having the same issue in VueJS. I found another article that suggested calling Auth.configure(amplifyConfig) instead of Amplify.configure(amplifyConfig). When I sign in with Google, it is no longer calling the token endpoint twice. This leads me to believe that the main Amplify configure function is perhaps configuring something twice??? I am also using the Amplify API library which depends on the config, so I call API.configure(amplifyConfig). I know this isn't the proper way of doing it, but so far it is giving me the best results.

@iamcgn
Copy link

iamcgn commented Nov 28, 2020

Thanks, @Jwb81, Auth.configure(amplifyConfig) works for me. Glancing through the code, it's clear that the Auth.configure is actually called twice. The first time it appears the intention is to pass in a null config but when it makes the call Amplify.register(Auth); at the bottom of the file Amplify.register calls Auth.configure() again with an empty object (Amplify's private _config property defaults to {} rather than null or undefined). Then, later, Auth.configure() is called with the config we pass in to Amplify.configure().

I don't have time to dig any deeper, I just wanted to see if it looked like bypassing Amplify.configure() is leaving out anything important. It looks to me that it just bypasses the bug by not calling Auth.configure multiple times :).

@enzoames
Copy link

enzoames commented Dec 9, 2020

I am certain I am not calling Amplify.configure() multiple times. I have it declared at the top on my _app.js file for my nextjs app. Any progress on this issue or additional work arounds? thanks!!!

@ivmakk
Copy link

ivmakk commented Dec 9, 2020

Faced with the same issue on Angular 11 (but deep research shows that the issue isn't connected to the frontend framework). Helped to switch to the production mode in the local environment (for Angular CLI that's ng serve --prod=true).

In my case, the core of the issue is a broken singleton of imported amplify packages, that causes "doubled" initialization of some amplify components (in some cases they initialized even more than 2 times). As a result, only one Auth component gets actual state and configuration, and its phantom brother gets irrelevant data, but still subscribes to auth events and continues sending broken requests. Probably both of the instances uses the same (local) storage, that makes a mess of the whole app and destabilizes amplify functionality in various places.

So my recommendation as a quick solution
Check what exactly triggers token exchange (see requests to the https://*.amazoncognito.com/oauth2/token). If the call is triggered by the same package, but from different sources, then you need to force the bundler (e.g. webpack) to remove duplicated dependencies (probably it happens during tree shaking on minification phase).

amplify_doubled_auth_trigers
Requests triggered by the same OAuth.js, but from different packages (versions of the packs are equal):

  • webpack:///./node_modules/@aws-amplify/auth/lib-esm/OAuth/OAuth.js
  • webpack:///./node_modules/@aws-amplify/ui-components/node_modules/@aws-amplify/auth/lib/OAuth/OAuth.js

NOTE: by default, the most effective tree shaking & minification happens when enabled production build and fully skipped or less strict in dev mode (such modes existed in most popular bundlers out of the box). As a bit more complex solution – manually setup minification.

NOTE2: no matter how many Amplify.configure() called in the application (of course, you need in the app to fire it once), a lot of initialization steps happen even before Amplify.configure() called. To see in details how exactly amplify starts, you may set window.LOG_LEVEL = 'DEBUG' before all other scripts (important to set the variable before started parsing of amplify packages, otherwise - you will see logs partially, after it already initialized). In case of Angular I've added it to index.html template (src/index.html) as <head><!-- existed code --><script>window.LOG_LEVEL = 'DEBUG';</script></head>.

@ericclemmons
Copy link
Contributor

Closing, as #7718 (via v1.0.1) should resolve this duplication issue.

To install the latest version of @aws-amplify/ui-angular, for example:

npm install aws-amplify @aws-amplify/ui-angular
# or
yarn add aws-amplify @aws-amplify/ui-angular

Be sure to install aws-amplify, rather than @aws-amplify/core directly.
(aws-amplify will install @aws-amplify/core and other dependencies itself)

Let us know if you experience any issues! 🙏

@EvansDaniel
Copy link

EvansDaniel commented Apr 3, 2021

@ericclemmons Has that pull request been deployed? I am wondering if I should expect the extra call to /token to still be happening or if it's already deployed, what version I should be using so that this issue goes away?

At the moment for me, I still have to do @Jwb81's suggestion involving just calling Auth.configure and API.configure instead of Amplify.configure. This doesn't actually stop the /token endpoint from being called twice (and failing the second), but it does prevent the behavior described by @slatemates here.

Edit
I was incorrect. The second call to /token was still happening because I had an additional place in my application where I was calling Amplify.configure. I still have to do Auth.configure and API.configure instead Amplify.configure as has been previously pointed out though.

@asyschikov
Copy link

@ericclemmons I am still having the same error and I am not sure what the ui-angular package has to do with that, here is the code that causes Auth double initialisation: https://github.com/aws-amplify/amplify-js/blob/main/packages/auth/src/Auth.ts#L2201 . So Auth is always configured twice which results in duplicate token request in case of federated sign in.

@marklacroix
Copy link

I encountered this issue while using create-react-app and importing from @aws-amplify/ui-components. The root cause seems to be that webpack 4 uses obsolete package resolution rules inside .mjs files (see webpack/webpack#9329).

This causes dependencies inside @aws-amplify/ui-components to resolve to the CommonJS versions, while elsewhere those dependencies are resolved to ESM. The result is that, as @ivmakk describes above, the singletons in Auth are duplicated and we get the behavior observed in this issue.

Unfortunately, at the time of writing, there is not a simple resolution. create-react-app is still using webpack 4 and has no clear timeline for the upgrade to webpack 5. It is possible to override the rules in the webpack configuration; refer to above webpack issue for details. Choose your preferred way to customize the webpack configuration in create-react-app.

@github-actions
Copy link

github-actions bot commented Sep 9, 2022

This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.

Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels or Discussions for those types of questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Sep 9, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Auth Related to Auth components/category bug Something isn't working
Projects
None yet
Development

No branches or pull requests