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

Token not being passed to Cognito after IDP Authentication (Okta) #11570

Closed ranopriyo-neogy closed 1 year ago

ranopriyo-neogy commented 1 year ago

Before opening, please confirm:

JavaScript Framework

React

Amplify APIs

Authentication

Amplify Categories

auth

Environment information

``` System: OS: macOS 13.4.1 CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz Memory: 373.90 MB / 16.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 14.19.1 - ~/.nvm/versions/node/v14.19.1/bin/node Yarn: 1.22.17 - /usr/local/bin/yarn npm: 8.9.0 - ~/.nvm/versions/node/v14.19.1/bin/npm Browsers: Chrome: 114.0.5735.133 Safari: 16.5.1 npmPackages: @aws-amplify/cli: ^12.1.0-rc.2def814808.0 => 12.1.0-rc.2def814808.0 @aws-amplify/ui-react: ^5.0.3 => 5.0.3 @aws-amplify/ui-react-internal: undefined () @testing-library/jest-dom: ^5.16.5 => 5.16.5 @testing-library/react: ^13.4.0 => 13.4.0 @testing-library/user-event: ^13.5.0 => 13.5.0 react: ^18.2.0 => 18.2.0 react-dom: ^18.2.0 => 18.2.0 react-router-dom: ^6.14.0 => 6.14.0 react-scripts: 5.0.1 => 5.0.1 web-vitals: ^2.1.4 => 2.1.4 npmGlobalPackages: @aws-amplify/cli: 12.1.1 corepack: 0.10.0 gatsby-cli: 4.21.0 n: 9.1.0 npm-check-updates: 16.0.6 npm: 8.9.0 to: 0.2.9 typescript: 4.6.4 update: 0.7.4 ```

Describe the bug

I have deployed a simple React App and trying to add authentication on top of the App.js component. Here I am using Okta as an IDP configured manually to the Cognito user pool deployed using Amplify. The docs I followed for Okta and Cognito Integration is - cognito-okta-saml-identity-provider To add the auth component in App.js I followed the mentioned code provided in - AmplifyDocs

Using it I was able to get a button that on-click sends me to IDP (Okta) for authentication. The IDP authentication is successful however I observed the token that IDP should provide to Cognito was not being sent and I was again re-directed to the same page (With the button) to click for federation using IDP.

The Error I observed in the developer console log is..

Sign in failure ValidationException: 1 validation error detected: Value '{cognito-idp.us-east-1.amazonaws.com/us-east-xxx=}' at 'logins' failed to satisfy constraint: Map value must satisfy constraint: [Member must have length less than or equal to 50000, Member must have length greater than or equal to 1]
    at https://master.xxxx.amplifyapp.com/static/js/main.8b0c5a0f.js:2:249708
    at https://master.xxxxx.amplifyapp.com/static/js/main.8b0c5a0f.js:2:248783
    at Object.next (https://master.xxxxx.amplifyapp.com/static/js/main.8b0c5a0f.js:2:248888)
    at a (https://master.xxxx.amplifyapp.com/static/js/main.8b0c5a0f.js:2:247603)

On further researching it, I found the IDP token was not present for calls made to cognito-identity.us-east-1.amazonaws.com which informs Cognito that the user has been authenticated.

Logins: {cognito-idp.us-east-1.amazonaws.com/us-east-1_xxx: ""}
cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxx: ""

Expected behavior

Post authentication at Okta IDP, I should be able to able to get into the App.

Reproduction steps

  1. Clicking on the Hosted Amplify App
  2. Clicking on the Federated Button I added following docs
  3. Go to the developer console and there you can see the call fails with the above-mentioned Error post-IDP Authentication.

Code Snippet

Here is my code snippet for App.js

import { useEffect, useState } from 'react';
import { Amplify, Auth, Hub } from 'aws-amplify';
import awsConfig from './aws-exports';

// const isLocalhost = Boolean(
//   window.location.hostname === 'localhost' ||
//     // [::1] is the IPv6 localhost address.
//     window.location.hostname === '[::1]' ||
//     // 127.0.0.1/8 is considered localhost for IPv4.
//     window.location.hostname.match(
//       /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
//     )
// );

// Assuming you have two redirect URIs, and the first is for localhost and second is for production
const [
  // localRedirectSignIn,
  productionRedirectSignIn,
] = awsConfig.oauth.redirectSignIn;

const [
  productionRedirectSignOut,  
] = awsConfig.oauth.redirectSignOut;

const updatedAwsConfig = {
  ...awsConfig,
  oauth: {
    ...awsConfig.oauth,
    redirectSignIn: productionRedirectSignIn,
    redirectSignOut: productionRedirectSignOut,
  }
}

Amplify.configure(updatedAwsConfig);
Auth.configure(awsConfig);

function App() {
  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;
        default:
          console.log('')
      }
    });

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

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

  return (
    <div>
      <p>User: {user ? JSON.stringify(user.attributes) : 'None'}</p>
      {user ? (
        <button onClick={() => Auth.signOut()}>Sign Out</button>
      ) : (
        <button onClick={() => Auth.federatedSignIn()}>Federated Sign In</button>
      )}
    </div>
  );
}

export default App;

Log output

``` // Put your logs below this line ```

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_identity_pool_id": "us-east-1:xxxxxxx",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_xxx",
    "aws_user_pools_web_client_id": "xxxxx",
    "oauth": {
        "domain": "xxxx.auth.us-east-1.amazoncognito.com",
        "scope": [  
            "phone",
            "email",
            "openid",
            "profile",
            "aws.cognito.signin.user.admin"
        ],
        "redirectSignIn": "https://master.xxxx.amplifyapp.com/",
        "redirectSignOut": "https://master.xxxx.amplifyapp.com/",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS",
    "aws_cognito_username_attributes": [
        "EMAIL"
    ],
    "aws_cognito_social_providers": [
        "GOOGLE"
    ],
    "aws_cognito_signup_attributes": [
        "EMAIL"
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [
        "SMS"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 8,
        "passwordPolicyCharacters": []
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ]
};

export default awsmobile;

Manual configuration

App Client Cognito

Screenshot 2023-06-30 at 3 31 30 PM

Web Client Cognito

Screenshot 2023-06-30 at 3 33 07 PM

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

ranopriyo-neogy commented 1 year ago

Please close this issue..

The issue was using Amplify.configure(updatedAwsConfig); instead of Auth.configure(awsConfig); or Amplify.configure(awsConfig);

cwomack commented 1 year ago

Glad you were able to unblock yourself @ranopriyo-neogy! Let us know if you have any further issues!