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.44k stars 2.13k forks source link

Oauth Social login success but cannot authenticated user #8727

Closed seunghwako closed 3 years ago

seunghwako commented 3 years ago

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

GraphQL API

Amplify Categories

auth

Environment information

``` # Put output below this line System: OS: macOS 11.4 CPU: (8) x64 Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz Memory: 797.84 MB / 16.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 15.5.1 - /usr/local/bin/node Yarn: 1.22.10 - /usr/local/bin/yarn npm: 7.3.0 - /usr/local/bin/npm Browsers: Chrome: 92.0.4515.131 Safari: 14.1.1 npmPackages: @ampproject/toolbox-optimizer: undefined () @aws-amplify/cli: ^5.1.2 => 5.1.2 @babel/core: undefined () @babel/plugin-proposal-class-properties: ^7.13.0 => 7.13.0 (7.14.5) @babel/plugin-proposal-decorators: ^7.13.15 => 7.13.15 @emotion/babel-plugin: ^11.2.0 => 11.2.0 (11.3.0) @emotion/core: ^11.0.0 => 11.0.0 (10.1.1) @emotion/react: ^11.1.5 => 11.1.5 @emotion/styled: ^11.3.0 => 11.3.0 @types/node: ^14.14.37 => 14.14.37 (12.20.15, 14.14.41) @types/react: ^17.0.3 => 17.0.3 @types/react-cookies: ^0.1.0 => 0.1.0 @types/uuid: ^8.3.0 => 8.3.0 @typescript-eslint/eslint-plugin: ^4.19.0 => 4.19.0 amphtml-validator: undefined () arg: undefined () async-retry: undefined () async-sema: undefined () aws-amplify: ^4.2.1 => 4.2.1 babel-plugin-transform-typescript-metadata: ^0.3.2 => 0.3.2 bfj: undefined () cacache: undefined () cache-loader: undefined () ci-info: undefined () comment-json: undefined () compression: undefined () conf: undefined () content-type: undefined () cookie: undefined () cookie-cutter: ^0.2.0 => 0.2.0 core-decorators: ^0.20.0 => 0.20.0 css-loader: undefined () debug: undefined () devalue: undefined () emotion: ^11.0.0 => 11.0.0 escape-string-regexp: undefined () eslint: 7.2.0 => 7.2.0 (7.23.0) eslint-config-airbnb-typescript: ^12.3.1 => 12.3.1 eslint-config-prettier: ^8.1.0 => 8.1.0 eslint-import-resolver-typescript: ^2.4.0 => 2.4.0 eslint-plugin-import: 2.22.1 => 2.22.1 eslint-plugin-jsx-a11y: 6.4.1 => 6.4.1 eslint-plugin-prettier: ^3.3.1 => 3.3.1 eslint-plugin-react: 7.21.5 => 7.21.5 eslint-plugin-react-hooks: ^4.2.0 => 4.2.0 file-loader: undefined () find-cache-dir: undefined () find-up: undefined () formik: ^2.2.9 => 2.2.9 fresh: undefined () global: ^4.4.0 => 4.4.0 gzip-size: undefined () http-proxy: undefined () ignore-loader: undefined () is-animated: undefined () is-docker: undefined () is-wsl: undefined () json5: undefined () jsonwebtoken: undefined () loader-utils: undefined () lodash.curry: undefined () lru-cache: undefined () memo-parser: 0.2.1 mobx: ^6.2.0 => 6.2.0 mobx-react: ^7.2.0 => 7.2.0 nanoid: undefined () neo-async: undefined () new-plugin-package: 1.0.0 next: ^10.0.9 => 10.0.9 next-cookies: ^2.0.3 => 2.0.3 ora: undefined () postcss-flexbugs-fixes: undefined () postcss-loader: undefined () postcss-preset-env: undefined () postcss-scss: undefined () prettier: ^2.2.1 => 2.2.1 (1.19.1) prettier-eslint: ^12.0.0 => 12.0.0 react: ^17.0.2 => 17.0.2 react-cookie: ^4.0.3 => 4.0.3 react-dom: ^17.0.2 => 17.0.2 react-helmet: ^6.1.0 => 6.1.0 react-messenger-customer-chat: ^0.8.0 => 0.8.0 react-script-tag: ^1.1.2 => 1.1.2 react-select: ^4.3.0 => 4.3.0 react-slick: ^0.28.1 => 0.28.1 react-toast-notifications: ^2.4.3 => 2.4.3 recast: undefined () reflect-metadata: ^0.1.13 => 0.1.13 remove: ^0.1.5 => 0.1.5 resolve-url-loader: undefined () sass-loader: undefined () schema-utils: undefined () semver: undefined () send: undefined () slick-carousel: ^1.8.1 => 1.8.1 source-map: undefined () string-hash: undefined () strip-ansi: undefined () stylelint: ^13.12.0 => 13.12.0 stylelint-config-standard: ^21.0.0 => 21.0.0 stylelint-config-styled-components: ^0.1.1 => 0.1.1 stylelint-order: ^4.1.0 => 4.1.0 stylelint-processor-styled-components: ^1.10.0 => 1.10.0 stylelint-scss: ^3.19.0 => 3.19.0 terser: undefined () text-table: undefined () thread-loader: undefined () typescript: ^4.2.3 => 4.2.3 (3.9.10, 3.9.9) unistore: undefined () url-loader: ^4.1.1 => 4.1.1 web-vitals: undefined () webpack: undefined () webpack-sources: undefined () yup: ^0.32.9 => 0.32.9 zen-observable: ^0.8.15 => 0.8.15 (0.7.1) npmGlobalPackages: @aws-amplify/cli: 4.41.0 npm: 7.3.0 yarn: 1.22.10

Describe the bug

Although oauth social login is successful and user information is put into userpool,"Uncaught (in promise) The user is not authenticated" error occurs.

Facebook is redirected to https://www.tintinlive.vn/#_=_.

Google is redirected to https://tintinlive/#.

Expected behavior

User authentication and login must be successful with the redirection link running correctly.

Reproduction steps

On the login page, click each social login button and go home through the redirection link.

Code Snippet

// Put your code below this line.

  function loginWithGoogle() {
    Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google });
    setCookie('socialUser', 'social');
  }

  function loginWithFacebook() {
    Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Facebook });
    setCookie('socialUser', 'social');
  }

 <>
      <FormWrapper name='form' onSubmit={formik.handleSubmit}>
        <Self>
          <Layout>
            <SocialBlock>
              <FacebookDiv onClick={loginWithFacebook}>
                <SocialFacebook />
                <SocialTextFacebook>Login with Facebook</SocialTextFacebook>
              </FacebookDiv>
              <GoogleDiv onClick={loginWithGoogle}>
                <SocialGoogle />
                <SocialTextGoogle>Login with Google</SocialTextGoogle>
              </GoogleDiv>
            </SocialBlock>
          </Layout>
        </Self>

    </>
  );

### Log output

<details>

// Put your logs below this line

Uncaught (in promise) The user is not authenticated

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": "ap-northeast-2", "aws_cognito_identity_pool_id": "ap-northeast-2:e12b4f97-77b9-4f30-be89-f69b21abed29", "aws_cognito_region": "ap-northeast-2", "aws_user_pools_id": "ap-northeast-2_TaAG9EBUR", "aws_user_pools_web_client_id": "5il68icuso99k6fqpk17vqsfol", "oauth": { "domain": "fined256c73b-d256c73b-main.auth.ap-northeast-2.amazoncognito.com", "scope": [ "phone", "email", "openid", "profile", "aws.cognito.signin.user.admin" ], "redirectSignIn": "https://tintinlive.vn/", "redirectSignOut": "https://tintinlive.vn/", "responseType": "code" }, "federationTarget": "COGNITO_USER_POOLS", "aws_user_files_s3_bucket": "finef05006faa82440a6bcdd7a319adcaa4b181850-main", "aws_user_files_s3_bucket_region": "ap-northeast-2", "aws_appsync_graphqlEndpoint": "https://4ehcsu663zcl7bqu6pf4i3s6km.appsync-api.ap-northeast-2.amazonaws.com/graphql", "aws_appsync_region": "ap-northeast-2", "aws_appsync_authenticationType": "API_KEY", "aws_appsync_apiKey": "da2-rndd4gesqjfuvgkid6ommgnody", "aws_cloud_logic_custom": [ { "name": "AdminQueries", "endpoint": "https://5oy84n7aof.execute-api.ap-northeast-2.amazonaws.com/main", "region": "ap-northeast-2" } ] };

export default awsmobile;

Manual configuration

No response

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

chrisbonifacio commented 3 years ago

Hey @seunghwako πŸ‘‹ thanks for raising this! Could you provide the code where you're configuring Amplify and attempting to get the user data?

seunghwako commented 3 years ago

HI! @chrisbonifacio. I provide the amplify auth's parameter.json code, amplify auth signin document customizing code and Our Rendering code! Thanks! Current env is main But I change env to dev, It works well. The difference between the two environments is only the difference between redirection link being local or not.

amplify/auth/fined0f28391/parametet.json { "identityPoolName": "fined0f28391_identitypool_d0f28391", "allowUnauthenticatedIdentities": true, "resourceNameTruncated": "fined0f28391", "userPoolName": "fined0f28391_userpool_d0f28391", "autoVerifiedAttributes": [ "email" ], "mfaConfiguration": "OFF", "mfaTypes": [ "SMS Text Message" ], "smsAuthenticationMessage": "Your authentication code is {####}", "smsVerificationMessage": "Your verification code is {####}", "emailVerificationSubject": "Your verification code", "emailVerificationMessage": "Your verification code is {####}", "defaultPasswordPolicy": false, "passwordPolicyMinLength": 8, "passwordPolicyCharacters": [], "requiredAttributes": [ "email" ], "userpoolClientGenerateSecret": true, "userpoolClientRefreshTokenValidity": 30, "userpoolClientWriteAttributes": [ "email" ], "userpoolClientReadAttributes": [ "email" ], "userpoolClientLambdaRole": "fined0d0f28391_userpoolclient_lambda_role", "userpoolClientSetAttributes": false, "sharedId": "d0f28391", "resourceName": "fined0f28391", "authSelections": "identityPoolAndUserPool", "authRoleArn": { "Fn::GetAtt": [ "AuthRole", "Arn" ] }, "unauthRoleArn": { "Fn::GetAtt": [ "UnauthRole", "Arn" ] }, "useDefault": "defaultSocial", "hostedUI": true, "userPoolGroupList": [ "admin", "admin" ], "serviceName": "Cognito", "dependsOn": [], "hostedUIDomainName": "fined256c73b-d256c73b", "authProvidersUserPool": [ "Facebook", "Google" ], "hostedUIProviderMeta": "[{\"ProviderName\":\"Facebook\",\"authorize_scopes\":\"email,public_profile\",\"AttributeMapping\":{\"email\":\"email\",\"username\":\"id\"}},{\"ProviderName\":\"Google\",\"authorize_scopes\":\"openid email profile\",\"AttributeMapping\":{\"email\":\"email\",\"username\":\"sub\"}}]", "oAuthMetadata": "{\"AllowedOAuthFlows\":[\"code\"],\"AllowedOAuthScopes\":[\"phone\",\"email\",\"openid\",\"profile\",\"aws.cognito.signin.user.admin\"],\"CallbackURLs\":[\"https://tintinlive.com/\"],\"LogoutURLs\":[\"https://tintinlive.com/\"]}" }

`import { CognitoHostedUIIdentityProvider } from '@aws-amplify/auth/lib/types';
import styled from '@emotion/styled';
import { Auth, Hub } from 'aws-amplify';
.
.
.
.
.
.
function loginWithGoogle() {
    Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google });
    setCookie('socialUser', 'social');
  }

  function loginWithFacebook() {
    Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Facebook });
    setCookie('socialUser', 'social');
  }

return(
<SocialBlock>
              <FacebookDiv onClick={loginWithFacebook}>
                <SocialFacebook />
                <SocialTextFacebook>Login with Facebook</SocialTextFacebook>
              </FacebookDiv>
              <GoogleDiv onClick={loginWithGoogle}>
                <SocialGoogle />
                <SocialTextGoogle>Login with Google</SocialTextGoogle>
              </GoogleDiv>
            </SocialBlock>
);`

pages/api/signin.tsx

`/* eslint-disable no-console */
import { Auth } from 'aws-amplify';

const Signin = async (username, password) => {
  try {
    await Auth.signIn(username, password);
    const user = await Auth.currentAuthenticatedUser();
    const {
      signInUserSession: { idToken },
    } = user;
    return idToken;
  } catch (error) {
    console.log('error: ', error);
    switch (error.code) {
      case 'NetworkError':
        console.log('error1: ', error);
        // λ„€νŠΈμ›Œν¬μ—λŸ¬κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.
        return 'Unknown';
      case 'NotAuthorizedException':
        console.log('error2: ', error);
        // μ•„μ΄λ””λ‚˜ λΉ„λ°€λ²ˆν˜Έκ°€ λ‹€λ¦…λ‹ˆλ‹€.
        return 'Unknown';
      case 'UserNotConfirmedException':
        console.log('error3: ', error);
        // μ΄λ©”μΌμ—μ„œ μΈμ¦μ½”λ“œλ₯Ό 확인 ν›„ λ“±λ‘ν•΄μ£Όμ„Έμš”.
        return 'Unknown';
      case 'UserNotFoundException':
        console.log('error4: ', error);
        // κ°€μž…μž 정보가 μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.
        return 'Unknown';
      default:
        return 'Unknown';
    }
  }
};

export default Signin;`
chrisbonifacio commented 3 years ago

Is the dev environment hosted somewhere that I can use to compare?

Also, are you calling Amplify.configure like so?

Amplify.configure({ ...awsconfig, ssr: true });

I would also check that you have this setting in your next.config.js file

module.exports = {
  trailingSlash: true
}
seunghwako commented 3 years ago

Yes, Our dev environment hosted link is 'https://develop.tintinlive.com/signin' and main environment hosted link is 'https://tintinlive.com/signin' Also I calling Amplify.configure like this

import config from '../src/aws-exports';

Amplify.configure({
  ...config,
  ssr: true,
});

My next.config.jssetting like this

module.exports = {
  webpack: config => {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['url-loader'],
    });

    return config;
  },
};

These setting are same like dev environment and main environment

chrisbonifacio commented 3 years ago

This is what happened when I tried to sign in with Google in the dev env.

Screen Shot 2021-08-13 at 3 08 21 PM

In the main env some info did get set to local storage but I noticed I'm redirected back to https://www.tintinlive.com/#

Screen Shot 2021-08-13 at 3 09 21 PM
chrisbonifacio commented 3 years ago

I also have a the pkce key which does not seem to be getting picked up by amplify on redirect

Screen Shot 2021-08-13 at 3 18 06 PM
chrisbonifacio commented 3 years ago

@hkjpotato have you seen this behavior before with OAuth or have some insight into why a user might be redirected back to the app but the pkce_key is left in session storage? In my reproduction, I see it for a split second before, I assume, Amplify picks it up and uses it in exchange for the code.

seunghwako commented 3 years ago

@chrisbonifacio I changed dev env user pool settings. However, the dev environment can only be tested in local. When I read your explanation, is it right to understand that localstorage use is a problem?

seunghwako commented 3 years ago

When I signed in local env, I can get these informations. 스크란샷 2021-08-17 α„‹α…©α„Œα…₯ᆫ 11 15 56

chrisbonifacio commented 3 years ago

@seunghwako localStorage is okay, Amplify sets the id, access, and refresh tokens there when the user authenticates successfully. This is a good sign because it means that you are logged in. The issue may instead be in the Client ID from google that was provided to the CLI. Maybe re-enter the Client ID and Secret from google in that environment? Make sure that there are no trailing spaces when copy/pasting.

seunghwako commented 3 years ago

@chrisbonifacio I re-entered Client Id and Secret from Google and Facebook on main environment in cli but still occur "The user is not authenicated" error. However, user information is successfully generated in cognito user pool.

chrisbonifacio commented 3 years ago

@seunghwako can you follow the steps listed in this comment on a related issue and post the responses here?

https://github.com/aws-amplify/amplify-js/issues/5723#issuecomment-869969225

update: after looking into the issue #8445 I think you are federating into identity pool directly, please kindly check the reply in that issue for the difference between different federation approaches.

We are looking into it and can you provide me the following information to help identify the root cause:

  1. Is your responseType in oauth config set to "code" instead of "token"?
  2. If so, can you help check if there is a network request sent to the token endpoint ({domain}/oauth2/token) and does it include code_verifier in its payload? Does the request succeed? (it will return the idToken/accessToken/refreshToken)
  3. besides, have you tried other idps like Google or Facebook? Does this issue happen only to SignInWithApple?

The code_verifier is the pkce we set during Auth.federateSignIn({provider}) and it was stored in the session storage in a browser environment.

Also, when we call Auth.federatedSignIn({ provider: "XXX", }), this will direct you to the authorize endpoint of cognito hosted UI, and then redirect to the third party login page. Since it is a different page, we lose the reference to the previous object, and thus need to use Hub to listener to the global event when redirected back (as suggested by @amhinson).

The only way to use Auth.federatedSign().then is when we directly federate into the identity pool.

Thanks ahead of time!

seunghwako commented 3 years ago

@chrisbonifacio My responseType is code. I checked request token at https://tintinlive.com/oauth2/token, I sent the error message like this 스크란샷 2021-08-25 α„‹α…©α„Œα…₯ᆫ 10 23 18

Also, I tried to use Hub like this, Is it correct code?

const [user, setUser] = useState(null);

  useEffect(() => {
    Hub.listen('auth', ({ payload: { event, data } }) => {
      switch (event) {
        case 'signIn':
        case 'cognitoHostedUI':
          getUser().then(userData => setUser(userData));
          break;
        case 'signOut':
          setUser(null);
          break;
        case 'signIn_failure':
        case 'cognitoHostedUI_failure':
          console.log('Sign in failure', data);
          break;
      }
    });

    getUser().then(userData => setUser(userData));
  }, []);

  function getUser() {
    return Auth.currentAuthenticatedUser()
      .then(userData => userData)
      .catch(() => console.log('Not signed in'));
  }

  function loginWithGoogle() {
    <div>
      <p>User: {user ? JSON.stringify(user.attributes) : 'None'}</p>
      {user ? (
        <button onClick={() => Auth.signOut()}>Sign Out</button>
      ) : (
        <button
          onClick={() => Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google })}
        >
          Federated Sign In
        </button>
      )}
    </div>;
    // Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Google });
    setCookie('socialUser', 'social');
  }

  function loginWithFacebook() {
    <div>
      <p>User: {user ? JSON.stringify(user.attributes) : 'None'}</p>
      {user ? (
        <button onClick={() => Auth.signOut()}>Sign Out</button>
      ) : (
        <button
          onClick={() =>
            Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Facebook })
          }
        >
          Federated Sign In
        </button>
      )}
    </div>;
    // Auth.federatedSignIn({ provider: CognitoHostedUIIdentityProvider.Facebook });
    setCookie('socialUser', 'social');
  }
chrisbonifacio commented 3 years ago

@seunghwako sorry for the delayed response. your code seems fine to me! are you still experiencing issues in that environment?

ashika01 commented 3 years ago

@seunghwako just for clarification, so everything works for u in dev env but not in prod because of difference in redirectURL?

If so, in the aws-exports.js could u manually try to update it to redirect to the correct/expected url based on which env u r in?

seunghwako commented 3 years ago

The only difference in dev's prod is the redirection url.

I manually try to update the correct/expected url of the aws-export.js file in each environment, but there were no changes.

chrisbonifacio commented 3 years ago

Hi @seunghwako apologies for the delay. It's difficult to tell what might be wrong with your OAuth from the details shared so far. I haven't been able to reproduce this behavior on my end either. Would you be willing to jump on a call to troubleshoot? If so, please feel free to schedule a time that works for you here.

Fitux commented 3 years ago

Hey @chrisbonifacio I'm having the same issue, were you able to reproduce the issue? If not I could schedule some time to help you reproduce it.

chrisbonifacio commented 3 years ago

Hi @Fitux ! Sure, feel free to set up a date and time that works for you!

Unfortunately, haven't been able to reproduce this behavior where OAuth seems to redirect successfully but user is still not considered authenticated πŸ˜•

seunghwako commented 3 years ago

Hi @Fitux! Did you go through the same situation as me?

chrisbonifacio commented 3 years ago

@Fitux @seunghwako So, after doing some digging and trying to reproduce the issue on my end, the only similarity I could find between your configurations that was different from mine was that you configs are using a custom domain. Unfortunately, the CLI does not support custom domains out of the box and so this is an issue that still needs to be addressed.

However, in the issue linked above, there is a thread of possible workarounds that may apply to you and might be worth trying such as configuring your oauth like so: https://github.com/aws-amplify/amplify-cli/issues/1880#issuecomment-859779866

I worked around this by adding something like this:

import config from "./aws-exports";
// Update Cognito Settings
config.oauth.domain = "staging.auth.xxxxx.app";
Amplify.configure(config);

Building upon kylekirkby answer: I did this:

import awsConfig from './aws-exports';
const updatedAwsConfig = {
    ...awsConfig,
    oauth: {
        ...awsConfig.oauth,
        domain: "auth.mycustomdomain.com",
        redirectSignIn: "https://" + location.hostname + "/singin/redirect/path/",
        redirectSignOut: "https://" + location.hostname + "/signout/redirect/path/"
    }
}
Amplify.configure(updatedAwsConfig);

Every redirect route must be configured with Amplify. The custom domain must be authorized in Route 53.

This works even if you have multiple websites (dev1, dev2, dev3 ) to redirect to: and amazon only redirects to the correct server. (answering the original question of venkatesh-kadiyala (OP).

Fitux commented 3 years ago

I think that comment is related to the Hosted UI which I'm not using right now

chrisbonifacio commented 3 years ago

@Fitux what steps did you take when setting up your custom domain in Amplify? I'm going through this documentation but I want to be sure that I'm recreating your configuration.

EDIT: I bought a domain on GoDaddy and added it to my Amplify app through the Amplify console following the steps after clicking on Add domain. I did not use Route 53, migrate the domain, or create a hosted zone myself but rather let Amplify automate that for me. Seems to be working so far with Google and Facebook OAuth logins.

Screen Shot 2021-09-29 at 2 06 56 PM
chrisbonifacio commented 3 years ago

@Fitux if you can screenshot that console error that mentions a 400 status code and invalid client from Cognito after the redirect from Google, please post it here so that I can share with the team.

Fitux commented 3 years ago

@chrisbonifacio

The way I created my hosted zone in Route 53 was to migrate the dns service from my domain in Godaddy to Route 53, which is basically make the Godaddy DNS name servers to point to the ones in AWS Route 53. Similarly to the guide below.

https://virtualizationreview.com/articles/2020/07/14/migrating-dns-services-aws.aspx

After I created my hosted zone in Route 53, I used the steps you mentioned about adding a domain, which is really easy because since you have already a hosted zone, you just need to selected when you want to add the domain and everything is setup really easy.

PS: About the screenshot I will post it in another post

Fitux commented 3 years ago

@chrisbonifacio

Here is the screenshot of the error when using an url that is not my custom domain

Screen Shot 2021-09-29 at 15 30 10
seunghwako commented 3 years ago

@Fitux @seunghwako So, after doing some digging and trying to reproduce the issue on my end, the only similarity I could find between your configurations that was different from mine was that you configs are using a custom domain. Unfortunately, the CLI does not support custom domains out of the box and so this is an issue that still needs to be addressed.

However, in the issue linked above, there is a thread of possible workarounds that may apply to you and might be worth trying such as configuring your oauth like so: aws-amplify/amplify-cli#1880 (comment)

I worked around this by adding something like this:

import config from "./aws-exports";
// Update Cognito Settings
config.oauth.domain = "staging.auth.xxxxx.app";
Amplify.configure(config);

Building upon kylekirkby answer: I did this:

import awsConfig from './aws-exports';
const updatedAwsConfig = {
    ...awsConfig,
    oauth: {
        ...awsConfig.oauth,
        domain: "auth.mycustomdomain.com",
        redirectSignIn: "https://" + location.hostname + "/singin/redirect/path/",
        redirectSignOut: "https://" + location.hostname + "/signout/redirect/path/"
    }
}
Amplify.configure(updatedAwsConfig);

Every redirect route must be configured with Amplify. The custom domain must be authorized in Route 53. This works even if you have multiple websites (dev1, dev2, dev3 ) to redirect to: and amazon only redirects to the correct server. (answering the original question of venkatesh-kadiyala (OP).

Hi @chrisbonifacio Can this be a way to solve my problem?

chrisbonifacio commented 3 years ago

@Fitux According to the docs, the error code you're getting is because:

unauthorized_client Client is not allowed for code grant flow or for refreshing tokens.

Could you double check your app client settings in Cognito and make sure you have these enabled?

chrisbonifacio commented 3 years ago

@seunghwako you should add this line above your amplify configuration and see what error you're getting from Auth after being redirected from Google during oauth flow. I'm still not exactly sure what the cause of the issue might be for you and this may help us find out.

Amplify.Logger.LOG_LEVEL = "DEBUG"

chrisbonifacio commented 3 years ago

Hi πŸ‘‹ Closing this as we have not heard back from you. If you are still experiencing this issue and in need of assistance, please feel free to comment and provide us with any information previously requested by our team members so we can re-open this issue and be better able to assist you. Thank you!

Fitux commented 3 years ago

Sorry I thought I did answer your querstion @chrisbonifacio Yeah I have those enabled, and the issue only happened when we used the url that was not the custom domain. I don't think the unauthorized_client is related to the main issue

chrisbonifacio commented 3 years ago

@Fitux sorry for the delay. If you're still experiencing this issue, can you open an issue and fill out the Bug Report form with your environment information? Going to close this issue since the original customer has not commented or provided any updates. Also, if you can still reproduce the issue, please export a HAR file so we can see and parse through the Network Activity.

namhong2001 commented 2 years ago

Amplify.Logger.LOG_LEVEL = "DEBUG"

This helped me find out the cause.

In my case, the error was like this image

and caused by this. image

It was a little hard to find openid is used to make username of account by facebook, but for this reason, "openid" is required.

github-actions[bot] commented 1 year ago

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.