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.41k stars 2.11k forks source link

Get error: 'POST https://cognito-identity.us-east-1.amazonaws.com/ 400'... while have allowed unauthorized access...need help.. #4658

Closed iam-yan closed 4 years ago

iam-yan commented 4 years ago

Which Category is your question related to? Auth

What AWS Services are you utilizing? Cognito, Lambda, APIGateway

Provide additional details e.g. code snippets When unauthorized user visits the web-app, everything works fine until API is called. The following bug would be threw: POST https://cognito-identity.us-east-1.amazonaws.com/ 400 What have I missed?

fyi:

  1. Everything goes where if in the app there is no usage of amplify except Auth

  2. I have allowed unauthorized access in my identity pool. But I feel the guest users are not actually assigned the unauthorized iam role... Because they can't access to the S3 files while in the iam_role this is allowed. resource yml:

    
    Resources:
    # The federated identity for our user pool to auth with
    CognitoIdentityPool:
    Type: AWS::Cognito::IdentityPool
    Properties:
      # Generate a name based on the stage
      IdentityPoolName: ******
      # Allow unathenticated users
      AllowUnauthenticatedIdentities: true
      # Link to our User Pool
      CognitoIdentityProviders:
        - ClientId:
            Ref: CognitoUserPoolClient
          ProviderName:
            Fn::GetAtt: ['CognitoUserPool', 'ProviderName']
    
    # IAM roles
    CognitoIdentityPoolRoles:
    Type: AWS::Cognito::IdentityPoolRoleAttachment
    Properties:
      IdentityPoolId:
        Ref: CognitoIdentityPool
      Roles:
        authenticated: !GetAtt CognitoAuthRole.Arn
        unauthenticated: !GetAtt CognitoUnauthRole.Arn
    
    # IAM role used for unauthenticated users
    CognitoUnauthRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: ******
      Path: /
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: 'Allow'
            Principal:
              Federated: 'cognito-identity.amazonaws.com'
            Action:
              - 'sts:AssumeRoleWithWebIdentity'
            Condition:
              StringEquals:
                'cognito-identity.amazonaws.com:aud':
                  Ref: CognitoIdentityPool
              'ForAnyValue:StringLike':
                'cognito-identity.amazonaws.com:amr': unauthenticated
      Policies:
        - PolicyName: 'CognitoUnauthorizedPolicy'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: 'Allow'
                Action:
                  - 'mobileanalytics:PutEvents'
                  - 'cognito-sync:*'
                Resource: '*'
    
              # Allow users to invoke our API
              - Effect: 'Allow'
                Action:
                  - 'execute-api:Invoke'
                Resource:
                  Fn::Join:
                    - ''
                    - - 'arn:aws:execute-api:'
                      - Ref: AWS::Region
                      - ':'
                      - Ref: AWS::AccountId
                      - ':'
                      - Ref: ApiGatewayRestApi
                      - '/*'
    
              # Allow unauthorized users to read files in s3
              - Effect: 'Allow'
                Action:
                  - 's3:GetObject'
                Resource:
                  - Fn::Join:
                      - ''
                      - - Fn::GetAtt: [AttachmentsBucket, Arn]
                        - '/*'
    
    # IAM role used for authenticated users
    CognitoAuthRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: ******
      Path: /
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: 'Allow'
            Principal:
              Federated: 'cognito-identity.amazonaws.com'
            Action:
              - 'sts:AssumeRoleWithWebIdentity'
            Condition:
              StringEquals:
                'cognito-identity.amazonaws.com:aud':
                  Ref: CognitoIdentityPool
              'ForAnyValue:StringLike':
                'cognito-identity.amazonaws.com:amr': authenticated
      Policies:
        - PolicyName: 'CognitoAuthorizedPolicy'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: 'Allow'
                Action:
                  - 'mobileanalytics:PutEvents'
                  - 'cognito-sync:*'
                  - 'cognito-identity:*'
                Resource: '*'
    
              # Allow users to invoke our API
              - Effect: 'Allow'
                Action:
                  - 'execute-api:Invoke'
                Resource:
                  Fn::Join:
                    - ''
                    - - 'arn:aws:execute-api:'
                      - Ref: AWS::Region
                      - ':'
                      - Ref: AWS::AccountId
                      - ':'
                      - Ref: ApiGatewayRestApi
                      - '/*'
    
              # Allow users to interact with s3
              - Effect: 'Allow'
                Action:
                  - 's3:*'
                Resource:
                  - Fn::Join:
                      - ''
                      - - Fn::GetAtt: [AttachmentsBucket, Arn]
                        - '/*'

Print out the Id of the Identity Pool that is created

Outputs: IdentityPoolId: Value: Ref: CognitoIdentityPool


## Sample Code
**_app**

import React, { useContext, useEffect } from 'react' import App from 'next/app' import Head from 'next/head' import { appStateContext, AppStateStore, logIn, signOut } from '../components' import '../assets/style.css'

import Amplify, { Auth, Hub, JS } from 'aws-amplify' import config from '../src/aws-config'

// Override browserOrNode to fix the bug in using Amplify with Nextjs. JS.browserOrNode = function() { const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined' const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null return { isBrowser: isBrowser, isNode: isNode, } }

// Manually configure. Amplify.configure(config)

const Layout = ({ children }) => { const { state, dispatch } = useContext(appStateContext)

// When the site is downloading the token. useEffect(() => { if (window.location.search.includes('?signedin=true&code') && !state.isAuthenticating) { dispatch({ type: 'set-authenticating', value: true }) } })

// Check auth on load. useEffect(() => { onLoad() }, [])

async function onLoad() { Hub.listen('auth', ({ payload: { event, data } }) => { switch (event) { case 'signIn': setImmediate(() => logIn(dispatch, data)) setImmediate(() => window.history.pushState({}, null, 'http://localhost:3000')) break case 'signOut': setTimeout(() => signOut(dispatch), 350) } })

if (!window.location.search.includes('?signedin=true')) {
  try {
    let user = await Auth.currentAuthenticatedUser()
    logIn(dispatch, user)
  } catch (e) {
    console.log(e)
  }
}
dispatch({ type: 'set-authenticating', value: false })

}

return ( <div className={#main-wrapper min-h-screen text-black flex flex-col}>

  <style jsx global>{`
    body {
      background: white
    }
  `}</style>
  {children}
</div>

) }

export default class MyApp extends App { render() { const { Component, pageProps } = this.props return (

)

} }

**Page**

// This page is for test. import { useEffect } from 'react' import { useRouter } from 'next/router' import { API } from 'aws-amplify'

export default () => { const router = useRouter()

useEffect(() => { async function onLoad() { try { const requestPath = ${router.asPath}/guest await API.get('improve', requestPath) } catch (e) { console.log(e) } } if (router.query.pid) onLoad() }, [router.query])

return

Test
}


## Headers
**General**

Request URL: https://cognito-identity.us-east-1.amazonaws.com/ Request Method: POST Status Code: 400 Remote Address: 127.0.0.1:1087 Referrer Policy: no-referrer-when-downgrade

**Response Headers**

access-control-allow-origin: * access-control-expose-headers: x-amzn-RequestId,x-amzn-ErrorType,x-amzn-ErrorMessage,Date content-length: 129 content-type: application/x-amz-json-1.1 date: Wed, 01 Jan 2020 07:11:43 GMT status: 400 x-amzn-errormessage: Access to Identity 'us-east-1:2decd9cb-2d9e-48b1-8095-f433a306a7e7' is forbidden. x-amzn-errortype: NotAuthorizedException: x-amzn-requestid: fd1e32ff-1db8-498a-8e3c-1c6f5d029a0b

**Request Headers**

:authority: cognito-identity.us-east-1.amazonaws.com :method: POST :path: / :scheme: https accept: / accept-encoding: gzip, deflate, br accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ja;q=0.6 content-length: 63 content-type: application/x-amz-json-1.1 origin: http://localhost:3000 referer: http://localhost:3000/projects/0000001-weapon-concept sec-fetch-mode: cors sec-fetch-site: cross-site user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36 x-amz-content-sha256: c2ed0f608a62b760872b5d09b890bb4e112d08d140c4e4e3bb91681c645bac88 x-amz-target: AWSCognitoIdentityService.GetCredentialsForIdentity x-amz-user-agent: aws-amplify/2.2.1 js aws-amplify/2.2.1 js callback

**Request Payload**

{IdentityId: "us-east-1:2decd9cb-2d9e-48b1-8095-f433a306a7e7"} IdentityId: "us-east-1:2decd9cb-2d9e-48b1-8095-f433a306a7e7"


## Package

{ "name": "next-tailwind-starter", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start" }, "dependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.26", "@fortawesome/free-brands-svg-icons": "^5.12.0", "@fortawesome/free-solid-svg-icons": "^5.12.0", "@fortawesome/react-fontawesome": "^0.1.8", "@zeit/next-css": "^1.0.1", "autoprefixer": "^9.7.3", "aws-amplify": "^2.2.1", "next": "^9.1.6", "prop-types": "^15.7.2", "react": "^16.12.0", "react-dom": "^16.12.0", "tailwindcss": "^1.1.4" } }

Amplifiyer commented 4 years ago

@juuyan, can you share your sample app code and also the full request and response (along with headers) for the failing requests? You can find them in the network tab of the browser developer console.

iam-yan commented 4 years ago

@Amplifiyer Hi updated. Thanks for your help.

iam-yan commented 4 years ago

@Amplifiyer , I think the problem is that the identity pool always assign a disabled/deleted identity to me. When I use another browser, it works fine here. So I cleared browser data and got it solved.

But how could I avoid it in the future?(like manually re-assign identity if the legacy one has issues...?)

Amplifiyer commented 4 years ago

@juuyan I can't say for sure how you ended up in that state (were you changing any auth configurations?). After clearing the cache, are you able to reproduce it consistently?

You can also turn the debug logs on for better troubleshooting in case it happens again and provide these logs https://aws-amplify.github.io/docs/js/logger

iam-yan commented 4 years ago

@Amplifiyer I am actually not sure whether I have disabled any identity by mistake. But I think this issue is led by "Cognito Identity Pool keeps assigning same identity to an unauthorized user even the identity is disabled/deleted".

Am I right on this?

If so can I and how should I clear the cached identity when it is disabled?

Amplifiyer commented 4 years ago

"Cognito Identity Pool keeps assigning same identity to an unauthorized user even the identity is disabled/deleted"

I'm not sure which issue you are referencing here. Can you provide the link of the issue?

Also are you able to reproduce it again? If yes, please provide detailed reproduction steps so we can try to debug it.

iam-yan commented 4 years ago

@Amplifiyer I failed to reproduce it. I tried to delete the identity id for the guest, but the identity pool recreate one when the guest visit the app again within the same environment...

I don't know why last time identity pool did not behavior like this but instead reassign the same disabled id to the guest.

I'd close the issue. Thanks for your support.

github-actions[bot] commented 3 years 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.