Closed seunghwako closed 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?
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;`
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
}
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.js
setting 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
This is what happened when I tried to sign in with Google in the dev env.
In the main env some info did get set to local storage but I noticed I'm redirected back to https://www.tintinlive.com/#
I also have a the pkce key which does not seem to be getting picked up by amplify on redirect
@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.
@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?
When I signed in local env, I can get these informations.
@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.
@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.
@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:
- Is your
responseType
in oauth config set to "code" instead of "token"?- If so, can you help check if there is a network request sent to the token endpoint (
{domain}/oauth2/token
) and does it includecode_verifier
in its payload? Does the request succeed? (it will return the idToken/accessToken/refreshToken)- besides, have you tried other idps like Google or Facebook? Does this issue happen only to
SignInWithApple
?The
code_verifier
is thepkce
we set duringAuth.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 theauthorize
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 useHub
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!
@chrisbonifacio My responseType is code. I checked request token at https://tintinlive.com/oauth2/token
, I sent the error message like this
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');
}
@seunghwako sorry for the delayed response. your code seems fine to me! are you still experiencing issues in that environment?
@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?
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.
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.
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.
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 π
Hi @Fitux! Did you go through the same situation as me?
@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).
I think that comment is related to the Hosted UI which I'm not using right now
@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.
@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.
@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
@chrisbonifacio
Here is the screenshot of the error when using an url that is not my custom domain
@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?
@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?
@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"
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!
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
@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.
Amplify.Logger.LOG_LEVEL = "DEBUG"
This helped me find out the cause.
In my case, the error was like this
and caused by this.
It was a little hard to find openid is used to make username of account by facebook, but for this reason, "openid" is required.
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.
Before opening, please confirm:
JavaScript Framework
Next.js
Amplify APIs
GraphQL API
Amplify Categories
auth
Environment information
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 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