Amplify-js: cognito-idp.eu-central-1.amazonaws.com: Access Token does not have required scopes (Http - 400)

Created on 15 Oct 2018  路  14Comments  路  Source: aws-amplify/amplify-js

* Which Category is your question related to? *
Auth

* What AWS Services are you utilizing? *
AWS Cognito

* Provide additional details e.g. code snippets *
For some requests to "cognito-idp.eu-central-1.amazonaws.com" I get the error:

x-amzn-errormessage: Access Token does not have required scopes
x-amzn-errortype: NotAuthorizedException:

I think that the call Auth.currentSession has this consequence.

Request Header:

Content-Type: application/x-amz-json-1.1
Origin: http://localhost:4200
Referer: http://localhost:4200/admin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
X-Amz-Target: AWSCognitoIdentityProviderService.GetUser
X-Amz-User-Agent: aws-amplify/0.1.x js

Request Payload:

AccessToken: "MyAccessToken"

Response Header:

access-control-allow-origin: *
access-control-expose-headers: x-amzn-RequestId,x-amzn-ErrorType,x-amzn-ErrorMessage,Date
content-length: 90
content-type: application/x-amz-json-1.1
date: Mon, 15 Oct 2018 15:25:00 GMT
status: 400
x-amzn-errormessage: Access Token does not have required scopes
x-amzn-errortype: NotAuthorizedException:
x-amzn-requestid: My Request ID

General:

Request URL: https://cognito-idp.eu-central-1.amazonaws.com/
Request Method: POST
Status Code: 400 
Remote Address: Remote-Adress
Referrer Policy: no-referrer-when-downgrade

The amplify Configuration (manual):

let amplifyConfig = {
  aws_appsync_graphqlEndpoint: config.getAppsyncConfig("aws_appsync_graphqlEndpoint"),
  aws_appsync_region: config.getAppsyncConfig("aws_appsync_region"),
  aws_appsync_authenticationType: config.getAppsyncConfig("aws_appsync_authenticationType"),
  aws_appsync_apiKey: config.getAppsyncConfig("aws_appsync_apiKey"),
  Auth: {
    identityPoolId: config.getCognitoConfig("identityPool"),

    // REQUIRED - Amazon Cognito Region
    region: config.getCognitoConfig("region"),

    // OPTIONAL - Amazon Cognito User Pool ID
    userPoolId: config.getCognitoConfig("userPool"),

    // OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
    userPoolWebClientId: config.getCognitoConfig("userPoolClient"),
  },
  Analytics: {
    disabled: true,
  },
  API: {
    graphql_endpoint: config.getAppsyncConfig("aws_appsync_graphqlEndpoint"),
    aws_appsync_region: config.getCognitoConfig("region"),
    aws_appsync_authenticationType: 'AMAZON_COGNITO_USER_POOLS', // You have configured Auth with Amazon Cognito User Pool ID and Web Client Id
  }
};

Amplify.configure(amplifyConfig);

On the configured IdentityPool, Enable access to unauthenticated identities is activated.
The UnauthRole has the following policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}

callstack in Browser:

zone.js:1050 POST https://cognito-idp.eu-central-1.amazonaws.com/ 400
(anonymous) @ zone.js:1050
request @ Client.js:47
refreshSession @ CognitoUser.js:1210
getSession @ CognitoUser.js:1171
(anonymous) @ Auth.js:951
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:3820
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
(anonymous) @ zone.js:872
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
onInvokeTask @ core.js:3811
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
drainMicroTaskQueue @ zone.js:595
Promise.then (async)
scheduleMicroTask @ zone.js:578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:410
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:252
scheduleResolveOrReject @ zone.js:862
ZoneAwarePromise.then @ zone.js:962
ZoneAwarePromise.catch @ zone.js:967
authEvent @ index.js:88
push../node_modules/@aws-amplify/analytics/lib/index.js.Analytics.onHubCapsule @ index.js:39
(anonymous) @ Hub.js:62
push../node_modules/@aws-amplify/core/lib/Hub.js.HubClass.toListeners @ Hub.js:60
push../node_modules/@aws-amplify/core/lib/Hub.js.HubClass.dispatch @ Hub.js:35
dispatchAuthEvent @ Auth.js:55
push../node_modules/@aws-amplify/auth/lib/Auth.js.AuthClass.configure @ Auth.js:186
(anonymous) @ Amplify.js:25
push../node_modules/@aws-amplify/core/lib/Amplify.js.Amplify.configure @ Amplify.js:24
./src/main.ts @ main.ts:45
__webpack_require__ @ bootstrap:76
0 @ main.ts:109
__webpack_require__ @ bootstrap:76
checkDeferredModules @ bootstrap:43
webpackJsonpCallback @ bootstrap:30
(anonymous) @ main.js:1

At the IdentityPool a UserPool is configured as Authentication Provider.

How can I solve this issue?

AppSync Auth

Most helpful comment

Hey there Chris,

I just ran into this. In our case it was that the "aws.cognito.signin.user.admin" under "Allowed OAuth Scopes" under "App client settings" of the pool was unchecked and checking that fixed it for us.

Good luck!

Cheers,

Mark C

PS we were using the hosted UI, cognito pool login

All 14 comments

@ChrisWun what's your aws_appsync_authenticationType?

@powerful23 its AMAZON_COGNITO_USER_POOLS.

@ChrisWun then I think there is nothing todo with the identity pool. I guess you need to configure your appsync service to accept tokens from user pools. @manueliglesias what do you think?

@ChrisWun can you provide more details about this error? Does this error happen when the app starts? Also can you provide some debug log by putting window.LOG_LEVEL='DEBUG' in your code?

@powerful23 sure.
There are 5 Log Statements after the call.

[DEBUG] 20:40.260 AuthClass - Getting current session
cognito-idp.eu-central-1.amazonaws.com/:1 POST https://cognito-idp.eu-central-1.amazonaws.com/ 400
{[DEBUG] 55:45.942 AuthClass - getting user data failed: {鈥}
{[DEBUG] 55:45.948 AuthClass - Getting the session from this user:: CognitoUser}
{[DEBUG] 55:45.951 AuthClass - Succeed to get the user session: CognitoUserSession}
{[DEBUG] 55:45.942 AuthClass - getting user data failed: {鈥}
[DEBUG] 55:45.942 AuthClass - getting user data failed:
code: "NotAuthorizedException"
message: "Access Token does not have required scopes"
name: "NotAuthorizedException"
__proto__: Object
__proto__: Object

To get the current Session succeeds. I can do AppSync graphql API calls. The App is working fine.
I just wondered why there are so many errors in the log.

I did not use the amplify cli to create the Cognito UserPool and identityPools. We are using Google sign in, and followed the tutorial to add Google sign in to the UserPool.

This error happens when the app starts.

Do you need more information?

@powerful23
Any updates on this issue?

Hey there Chris,

I just ran into this. In our case it was that the "aws.cognito.signin.user.admin" under "Allowed OAuth Scopes" under "App client settings" of the pool was unchecked and checking that fixed it for us.

Good luck!

Cheers,

Mark C

PS we were using the hosted UI, cognito pool login

@wanderingwalrus

Thanks for your reply. But "aws.cognito.signin.user.admin" under "Allowed OAuth Scopes" is checked in our UserPool. Unfortunately, it does not work for us.

@ChrisWun I just had this issue too. I checked "aws.cognito.signin.user.admin" under the "Allowed OAuth Scopes", which didn't fix the issue by itself. I also had to add "aws.cognito.signin.user.admin" to the scopes in the login URL.

Is it a good idea to use this scope for tokens just to avoid this error? If this scope is not used, it seems like the library should avoid making this request.

Is enabling this scope safe?

The aws.cognito.signin.user.admin scope grants access to Amazon Cognito User Pool API operations that require access tokens, such as UpdateUserAttributes and VerifyUserAttribute.

https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-idp-settings.html

To avoid this error, we hat to add 'aws.cognito.signin.user.admin' to TokenScopesArray in the authData for the CognitoAuth object of the 'amazon-cognito-auth-js' library.
We forgot it in the frontend project.

    const authData = {
      ClientId: this.config.getCognitoConfig('userPoolClient'),
      AppWebDomain: this.config.getCognitoConfig('authWebDomain'), // Exclude the "https://" part.
      TokenScopesArray: [
        'phone',
        'email',
        'openid',
        'aws.cognito.signin.user.admin',
        'profile',
      ], // like ['openid','email','phone']...
      RedirectUriSignIn: this.config.getCognitoConfig('redirectUriSignIn'),
      RedirectUriSignOut: this.config.getCognitoConfig('redirectUriSignOut'),
      IdentityProvider: this.config.getCognitoConfig('identityProvider'),
      UserPoolId: this.config.getCognitoConfig('userPool'),
      AdvancedSecurityDataCollectionFlag: false
    };

    const auth = new CognitoAuth(authData);

    auth.useCodeGrantFlow();

I close this issue, but am also interested in answers to the questions of @tbsf and @OndeVai .
Thanks for your replies!

@OndeVai It depends on the context but yes, sometimes you may want to avoid giving the aws.cognito.signin.user.admin scope to users. E.g. if you are using an external IdP, and it is the source of truth or if you rely on user attributes for authorization decisions.

@ChrisWun I just had this issue too. I checked "aws.cognito.signin.user.admin" under the "Allowed OAuth Scopes", which didn't fix the issue by itself. I also had to add "aws.cognito.signin.user.admin" to the scopes in the login URL.

thanks. i tried both changes, it works now.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CodySwannGT picture CodySwannGT  路  69Comments

kennu picture kennu  路  64Comments

jiachen247 picture jiachen247  路  79Comments

Benzer1406 picture Benzer1406  路  62Comments

jmandivarapu1 picture jmandivarapu1  路  49Comments