aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.42k stars 2.12k forks source link

V6 Federated sign in with Google returns OAuthSignInException #12999

Closed sriranjanivenkatesan closed 4 months ago

sriranjanivenkatesan commented 7 months ago

Before opening, please confirm:

JavaScript Framework

React

Amplify APIs

Authentication

Amplify Version

v6

Amplify Categories

auth

Backend

None

Environment information

``` # Put output below this line System: OS: Linux 5.15 Ubuntu 20.04.6 LTS (Focal Fossa) CPU: (8) x64 Intel(R) Core(TM) i7-1065G7 CPU @ 1.30GHz Memory: 1013.43 MB / 15.37 GB Container: Yes Shell: 5.0.17 - /bin/bash Binaries: Node: 19.7.0 - /usr/local/bin/node Yarn: 1.22.19 - /usr/local/bin/yarn npm: 9.8.1 - /usr/local/bin/npm Browsers: Chrome: 114.0.5735.106 npmPackages: @babel/core: ^7.22.9 => 7.22.11 @babel/plugin-proposal-class-properties: ^7.18.6 => 7.18.6 @babel/plugin-transform-runtime: ^7.22.9 => 7.22.10 @babel/preset-env: ^7.22.9 => 7.22.10 @babel/preset-react: ^7.22.5 => 7.22.5 @emotion/react: ^11.11.1 => 11.11.1 @emotion/styled: ^11.11.0 => 11.11.0 @mui/icons-material: ^5.14.3 => 5.14.9 @mui/lab: ^5.0.0-alpha.136 => 5.0.0-alpha.141 @mui/material: ^5.14.0 => 5.14.6 @mui/styles: ^5.14.0 => 5.14.6 @reduxjs/toolkit: ^1.9.5 => 1.9.5 @reduxjs/toolkit-query: 1.0.0 @reduxjs/toolkit-query-react: 1.0.0 @stripe/react-stripe-js: ^2.1.1 => 2.3.0 @stripe/stripe-js: ^1.54.1 => 1.54.2 @testing-library/jest-dom: ^5.16.5 => 5.17.0 @testing-library/react: ^14.0.0 => 14.0.0 @testing-library/react-hooks: ^8.0.1 => 8.0.1 @testing-library/user-event: ^14.4.3 => 14.4.3 ace-builds: ^1.23.4 => 1.25.0 apexcharts: ^3.41.0 => 3.42.0 aws-amplify: ^6.0.15 => 6.0.15 aws-amplify/adapter-core: undefined () aws-amplify/analytics: undefined () aws-amplify/analytics/kinesis: undefined () aws-amplify/analytics/kinesis-firehose: undefined () aws-amplify/analytics/personalize: undefined () aws-amplify/analytics/pinpoint: undefined () aws-amplify/api: undefined () aws-amplify/api/server: undefined () aws-amplify/auth: undefined () aws-amplify/auth/cognito: undefined () aws-amplify/auth/cognito/server: undefined () aws-amplify/auth/enable-oauth-listener: undefined () aws-amplify/auth/server: undefined () aws-amplify/datastore: undefined () aws-amplify/in-app-messaging: undefined () aws-amplify/in-app-messaging/pinpoint: undefined () aws-amplify/push-notifications: undefined () aws-amplify/push-notifications/pinpoint: undefined () aws-amplify/storage: undefined () aws-amplify/storage/s3: undefined () aws-amplify/storage/s3/server: undefined () aws-amplify/storage/server: undefined () aws-amplify/utils: undefined () axios: ^1.4.0 => 1.4.0 babel-jest: ^29.6.1 => 29.7.0 babel-loader: ^9.1.3 => 9.1.3 cjs-loader: ^0.1.0 => 0.1.0 compression-webpack-plugin: ^10.0.0 => 10.0.0 copy-to-clipboard: ^3.3.3 => 3.3.3 css-loader: ^6.8.1 => 6.8.1 date-fns: ^2.30.0 => 2.30.0 dotenv-webpack: ^8.0.1 => 8.0.1 draft-js: ^0.11.7 => 0.11.7 draftjs-to-html: ^0.9.1 => 0.9.1 elkjs: ^0.8.2 => 0.8.2 env-cmd: ^10.1.0 => 10.1.0 eslint: ^8.45.0 => 8.47.0 eslint-config-airbnb: ^19.0.4 => 19.0.4 eslint-config-prettier: ^8.8.0 => 8.10.0 eslint-config-react-app: ^7.0.1 => 7.0.1 eslint-plugin-import: ^2.27.5 => 2.28.1 eslint-plugin-jsx-a11y: ^6.7.1 => 6.7.1 eslint-plugin-prettier: ^5.0.0 => 5.0.0 eslint-plugin-react: ^7.32.2 => 7.33.2 eslint-plugin-react-hooks: ^4.6.0 => 4.6.0 file-loader: ^6.2.0 => 6.2.0 framer-motion: ^10.16.4 => 10.18.0 html-loader: ^4.2.0 => 4.2.0 html-to-draftjs: ^1.5.0 => 1.5.0 html-webpack-plugin: ^5.5.3 => 5.5.3 html2canvas: ^1.4.1 => 1.4.1 humanize-duration: ^3.29.0 => 3.29.0 husky: ^8.0.3 => 8.0.3 image-minimizer-webpack-plugin: ^3.8.3 => 3.8.3 image-webpack-loader: ^8.1.0 => 8.1.0 imagemin: ^8.0.1 => 8.0.1 (7.0.1) imagemin-optipng: ^8.0.0 => 8.0.0 imagemin-svgo: ^10.0.1 => 10.0.1 (9.0.0) immutable: ^4.3.2 => 4.3.4 (3.7.6) iso-3166-1-alpha-2: ^1.0.1 => 1.0.1 jest: ^29.6.1 => 29.7.0 js-yaml: ^4.1.0 => 4.1.0 (3.14.1) json-loader: ^0.5.7 => 0.5.7 lint-staged: ^13.2.3 => 13.3.0 mini-css-extract-plugin: ^2.7.6 => 2.7.6 moment: ^2.29.4 => 2.29.4 prettier: ^3.0.0 => 3.0.2 react: ^18.2.0 => 18.2.0 react-ace: ^10.1.0 => 10.1.0 react-apexcharts: ^1.4.0 => 1.4.1 react-beautiful-dnd: ^13.1.1 => 13.1.1 react-datepicker: ^4.16.0 => 4.16.0 react-dom: ^18.2.0 => 18.2.0 react-draft-wysiwyg: ^1.15.0 => 1.15.0 react-file-reader: ^1.1.4 => 1.1.4 react-google-recaptcha: ^3.1.0 => 3.1.0 react-infinite-scroll-component: ^6.1.0 => 6.1.0 react-joyride: ^2.5.4 => 2.5.5 react-json-view: ^1.21.3 => 1.21.3 react-redux: ^8.1.1 => 8.1.2 (7.2.9) react-router-dom: ^6.14.1 => 6.15.0 react-slick: ^0.29.0 => 0.29.0 react-syntax-highlighter: ^15.5.0 => 15.5.0 react-test-renderer: ^18.2.0 => 18.2.0 react-use: ^17.4.0 => 17.4.0 react-virtualized: ^9.22.5 => 9.22.5 react-virtuoso: ^4.6.2 => 4.6.3 react18-json-view: ^0.2.6 => 0.2.7 reactflow: ^11.7.4 => 11.8.3 redux: ^4.2.1 => 4.2.1 rimraf: ^5.0.1 => 5.0.1 (2.7.1, 3.0.2) sass-loader: ^13.3.2 => 13.3.2 slick-carousel: ^1.8.1 => 1.8.1 style-loader: ^3.3.3 => 3.3.3 svg-url-loader: ^8.0.0 => 8.0.0 url-loader: ^4.1.1 => 4.1.1 use-debounce: ^9.0.4 => 9.0.4 use-react-screenshot: ^3.0.0 => 3.0.0 use-react-screenshot-example: 0.0.0 webpack: ^5.88.1 => 5.88.2 webpack-cli: ^5.1.4 => 5.1.4 webpack-dev-server: ^4.15.1 => 4.15.1 yaml: ^2.3.1 => 2.3.1 (1.10.2) yaml-loader: ^0.8.0 => 0.8.0 yarn-upgrade-all: ^0.7.2 => 0.7.2 npmGlobalPackages: @aws-amplify/cli: 12.10.1 corepack: 0.16.0 js-yaml: 4.1.0 n: 9.0.1 npm: 9.8.1 serve: 14.2.0 sonarqube-scanner: 3.0.1 wscat: 5.2.0 yaml-to-json: 0.3.0 yarn: 1.22.19 ```

Describe the bug

Expected behavior

Reproduction steps

  1. Upgraded amplify to v6.0.15: npm install aws-amplify@6.0.15
  2. Ran the amplify pull command which generated the amplifyconfiguration.json file
  3. Ran yarn start and clicked on the Sign in with Google button to trigger the sign in.
  4. Sign in redirects to the page of google accounts, and the required account is selected
  5. The page navigates back to the app's login page with the above exception instead of logging in and redirecting to the landing page of the app

Code Snippet

// Put your code below this line.

// The federated sign in is called from the code as follows:
    async function googleLoginCode() {
        await signInWithRedirect({ provider: 'Google' });
    }

// Hub is configured as follows:
useEffect(() => {
        const unsubscribe = Hub.listen('auth', ({ payload: { event, data } }) => {
            // eslint-disable-next-line default-case
            switch (event) {
                case 'signIn_failure':
                case 'signInWithRedirect_failure':
                case 'cognitoHostedUI_failure':
                case 'customState_failure':
                    window.localStorage.setItem('isFederatedError', 'true');
                    if (
                        data?.error?.message === 'User+is+not+enabled' ||
                        data?.error?.message === 'User+is+disabled.+' ||
                        location?.search?.includes('User+is+not+enabled') ||
                        location?.search?.includes('User+is+disabled.+')
                    ) {
                        window.localStorage.setItem(
                            'federatedError',
                            'Sign up successful.You are yet to be activated. Please contact the administrator.'
                        );
                    } else if (
                        data?.error?.message ===
                        'PreSignUp+failed+with+error+Sorry%2C+User+already+exist+with+same+email.+'
                    ) {
                        window.localStorage.setItem('federatedError', 'User already exist with same email.');
                    } else {
                        window.localStorage.setItem('federatedError', data?.error?.message);
                    }
                    break;
                case 'signInWithRedirect':
                    triggerHub();
                    break;
            }
        });

        // fetchAuthSession().
        //  then(user => {
        //      if (user && user?.tokens && user?.tokens?.idToken?.payload) {
        //      }
        //      else navigate('/login');
        //  })
        //  .catch(() => {
        //      navigate('/login');
        //  });
        // eslint-disable-next-line no-use-before-define
        getUser();

        return unsubscribe;
    }, []);

    const getUser = async () => {
        try {
            // eslint-disable-next-line no-unused-vars
            const currentUser = await getCurrentUser();
        } catch (error) {
            navigate('/login');
        }
    };

Log output

``` // Put your logs below this line { "event": "signInWithRedirect_failure", "data": { "error": { "name": "OAuthSignInException", "recoverySuggestion": "Make sure Cognito Hosted UI has been configured correctly" } } } ```

aws-exports.js

/* eslint-disable */
// WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsmobile = {
    "aws_project_region": "us-east-1",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_******",
    "aws_user_pools_web_client_id": "**********",
    "oauth": {
        "domain": "auth.int.covalent.xyz.auth.us-east-1.amazoncognito.com",
        "scope": [
            "aws.cognito.signin.user.admin",
            "email",
            "openid",
            "phone",
            "profile"
        ],
        "redirectSignIn": "http://localhost:8080/",
        "redirectSignOut": "http://localhost:8080/login/",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS",
    "aws_cognito_username_attributes": [],
    "aws_cognito_social_providers": [
        "GOOGLE"
    ],
    "aws_cognito_signup_attributes": [
        "GIVEN_NAME",
        "FAMILY_NAME",
        "EMAIL"
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 6,
        "passwordPolicyCharacters": []
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ]
};

export default awsmobile;

Manual configuration

{
    "aws_project_region": "us-east-1",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_******",
    "aws_user_pools_web_client_id": "********",
    "oauth": {
        "domain": "auth.int.covalent.xyz.auth.us-east-1.amazoncognito.com",
        "scope": ["aws.cognito.signin.user.admin", "email", "openid", "phone", "profile"],
        "redirectSignIn": "http://localhost:8080/",
        "redirectSignOut": "http://localhost:8080/login/",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS",
    "aws_cognito_username_attributes": [],
    "aws_cognito_social_providers": ["GOOGLE"],
    "aws_cognito_signup_attributes": ["GIVEN_NAME", "FAMILY_NAME", "EMAIL"],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 6,
        "passwordPolicyCharacters": []
    },
    "aws_cognito_verification_mechanisms": ["EMAIL"]
}

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

nadetastic commented 7 months ago

HI @sriranjanivenkatesan thank you for opening this issue. I've attempted to reproduce it unsuccessfully so far, but wanted to suggest on small but potentially helpful action - since you were upgrading between two major versions, could you try deleting your node_modules as well as package-lock.json file and reinstalling your dependencies if you haven't done so yet?

Additionally if you check local storage, can you share what values you see in there that are specific to Amplify Auth?

sriranjanivenkatesan commented 7 months ago

hello @nadetastic , thanks for the suggestion. We tried deleting the node_modules,package-lock and reinstalling. But still getting the same issue. As you can see below, this is our local storage, currently with null values. image

cc: @wjcunningham7

pedroSoaresll commented 6 months ago

I am facing the same issue in the same situation.

{
    "event": "signInWithRedirect_failure",
    "data": {
        "error": {
            "name": "OAuthSignInException",
            "recoverySuggestion": "Make sure Cognito Hosted UI has been configured correctly"
        }
    }
}

This is the returned URL params after login with Google

http://localhost:3000/clients/login?code=f8467056-8f9e-420c-b577-0198657a3e9f&state=94fhRV9INPzYguOZAENR4qpTp9RZmDbn

I got a 400 Bad Request at this request https://hairqueue-web.auth.us-east-1.amazoncognito.com/oauth2/token

Response:

{
    "error": "invalid_client"
}

Payload:

grant_type: authorization_code
code: f8467056-8f9e-420c-b577-0198657a3e9f
client_id: 6on8j0kq741oqmv5qaok9a3h09
redirect_uri: http://localhost:3000/clients/login
code_verifier: gerq4mrMS0buUHEdEDIKPPd8Te0569XzMCtCFyxNIPfNWubjm8Gx3CM6QfsGcl8V9sYHgiUDijz2pHRgB9OihoLPrP5gwyFjS7RnnIwQtytRE42wy6bqRrLOaHH7Apxl

I keep trying to solve this problem, if I have news I share it here.


Looking at this documentation, AWS said that provably the client_id|client_secret is nonexistent at authorization header. But looking at request headers, I could not see any authorization presented there.

Request header detailed :authority: hairqueue-web.auth.us-east-1.amazoncognito.com :method: POST :path: /oauth2/token :scheme: https Accept: */* Accept-Encoding: gzip, deflate, br, zstd Accept-Language: en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7 Content-Length: 312 Content-Type: application/x-www-form-urlencoded Origin: http://localhost:3000 Referer: http://localhost:3000/ Sec-Ch-Ua: "Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122" Sec-Ch-Ua-Mobile: ?1 Sec-Ch-Ua-Platform: "Android" Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36 X-Amz-User-Agent: aws-amplify/6.0.18 auth/36 framework/2

invalid_client Client authentication failed. For example, when the client includes client_id and client_secret in the authorization header, but there's no such client with that client_id and client_secret.

should it be a problem?

pedroSoaresll commented 6 months ago

I am facing the same issue in the same situation.

{
    "event": "signInWithRedirect_failure",
    "data": {
        "error": {
            "name": "OAuthSignInException",
            "recoverySuggestion": "Make sure Cognito Hosted UI has been configured correctly"
        }
    }
}

This is the returned URL params after login with Google

http://localhost:3000/clients/login?code=f8467056-8f9e-420c-b577-0198657a3e9f&state=94fhRV9INPzYguOZAENR4qpTp9RZmDbn

I got a 400 Bad Request at this request https://hairqueue-web.auth.us-east-1.amazoncognito.com/oauth2/token

Response:

{
    "error": "invalid_client"
}

Payload:

grant_type: authorization_code
code: f8467056-8f9e-420c-b577-0198657a3e9f
client_id: 6on8j0kq741oqmv5qaok9a3h09
redirect_uri: http://localhost:3000/clients/login
code_verifier: gerq4mrMS0buUHEdEDIKPPd8Te0569XzMCtCFyxNIPfNWubjm8Gx3CM6QfsGcl8V9sYHgiUDijz2pHRgB9OihoLPrP5gwyFjS7RnnIwQtytRE42wy6bqRrLOaHH7Apxl

I keep trying to solve this problem, if I have news I share it here.


Looking at this documentation, AWS said that provably the client_id|client_secret is nonexistent at authorization header. But looking at request headers, I could not see any authorization presented there.

Request header detailed :authority: hairqueue-web.auth.us-east-1.amazoncognito.com :method: POST :path: /oauth2/token :scheme: https Accept: */* Accept-Encoding: gzip, deflate, br, zstd Accept-Language: en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7 Content-Length: 312 Content-Type: application/x-www-form-URL-encoded Origin: http://localhost:3000 Referer: http://localhost:3000/ Sec-Ch-Ua: "Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122" Sec-Ch-Ua-Mobile: ?1 Sec-Ch-Ua-Platform: "Android" Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36 X-Amz-User-Agent: aws-amplify/6.0.18 auth/36 framework/2

invalid_client Client authentication failed. For example, when the client includes client_id and client_secret in the authorization header, but there's no such client with that client_id and client_secret.

Should it be a problem?

I am not having this error anymore. In my case, it was happening because I was using OAuth Google credentials that were automatically created by Firebase authentication. (I don't know exactly the reason for not working with AWS Cognito.

The solution for me: I created another credential from scratch (very simple) on the Google Cloud Platform and configured that in AWS Cognito.

Result: Now I can sign in using Google Provider and it is correctly generating tokens for the user authenticated.

israx commented 6 months ago

hello @sriranjanivenkatesan . Can you confirm if the following flow is valid ?

call signInWithRedirect -> redirect to social provider UI -> authenticate with social provider -> redirect back to the app -> url contains code and state query params -> authentication fails.

Also can you confirm if the error you are experiencing is coming from the customState_failure hub event ?

sriranjanivenkatesan commented 6 months ago

hello @israx , yeah the flow is right. But the event is signInWithRedirect_failure cc: @Prasy12

israx commented 6 months ago

The User cancelled OAuth flow. error message is usually thrown when the library is not able to find either the code or state query parameters. However your redirectURI does contain code and state. Is it possible for you to setup a breakpoint right before getting this error and console log this window.location.href ?

Also can you test this flow in different browsers, chrome, firefox and safari ?

nadetastic commented 6 months ago

Hi @sriranjanivenkatesan wanted to follow up here. Have you had a chance to review the comment from @israx above?

sriranjanivenkatesan commented 6 months ago

hello @nadetastic @israx Thanks for your patience:) Yeah I tried setting up the breakpoint in both the Hub function and the preceding Amplify.mjs file and I am getting ''http://localhost:8080/login' though I can see the code and state in the top as shown in below image googleHref

Tried with chrome and firefox, the issue seems to persist in both.

pedroSoaresll commented 6 months ago

hello @nadetastic @israx Thanks for your patience:) Yeah I tried setting up the breakpoint in both the Hub function and the preceding Amplify.mjs file and I am getting ''http://localhost:8080/login' though I can see the code and state in the top as shown in below image googleHref

Tried with chrome and firefox, the issue seems to persist in both.

It looks that after the login flow, it is not redirecting to the /login page but to the / page. Does it correct? I am supposing it because of the URL that the devtools window is showing at the top window bar.

if the Hub.listener logic is on the /login page but the redirect is moving the client to the / page, it probably is a problem to correctly complete the sign in flow.

speedhawk21 commented 5 months ago

hello @nadetastic @israx Thanks for your patience:) Yeah I tried setting up the breakpoint in both the Hub function and the preceding Amplify.mjs file and I am getting ''http://localhost:8080/login' though I can see the code and state in the top as shown in below image googleHref Tried with chrome and firefox, the issue seems to persist in both.

It looks that after the login flow, it is not redirecting to the /login page but to the / page. Does it correct? I am supposing it because of the URL that the devtools window is showing at the top window bar.

if the Hub.listener logic is on the /login page but the redirect is moving the client to the / page, it probably is a problem to correctly complete the sign in flow.

This was the issue I ran into as well. Make sure you have your routes properly defined as a broken route will also throw this same error. Thank you Pedro!

cwomack commented 5 months ago

@sriranjanivenkatesan, can you confirm if your redirect URL's in the Cognito console for the Hosted UI align with the redirect sign in/out in your config? I'm wondering if there's a mismatch between these. And are there any changes (beyond the imports and API names being called) when migrating from v5 to v6?

@speedhawk21 and @speedhawk21, thank you for the additional comments and glad to hear you're both unblocked.

cwomack commented 5 months ago

@sriranjanivenkatesan, can you see if upgrading to the latest version of Amplify (or anything after v6.0.23) gives you any different behavior? There were changes to the OAuth flow in that version that could help with the issue here.

Ikraam-Rasheed commented 4 months ago

@sriranjanivenkatesan, I came across same issue yesterday, signInwithRedirect was working fine on local but was giving same error as you mentioned above on prod,

my flow was like:

  1. mydomain.com/auth/login (Initiate Sign In with Redirect)
  2. mydomain.com/api/redirect (redirect signIn url)

On my redirect page, I was trying to fetch Session and after success, i was routing myself to main/home page. something like this, NOT EXACT CODE

 fetchAuthSession().then((session) => {
      //store cookie here
    }).finally(()=>{
        router.push("/")
    });

but i was getting the same error.

How I solved it:

I changed my redirect signIn url

from: mydomain.com/api/redirect to: mydomain.com/auth/login

from where i was initiating my signIn request and fetchSession there. It worked for me

Possible Issues:

Code Received -> you change your route/perform action -> Oauth Flow completes

cwomack commented 4 months ago

Thank you for the additional context/comment above, @Ikraam-Rasheed!

@sriranjanivenkatesan, I'll close out this issue since we haven't heard back from you (but others have commented as resolved). If you are still experiencing this, please feel free to reply back and provide any information previously requested and we'd be happy to re-open the issue.