Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Cognito hosted UI and Amplify Auth with authorization code OAuth flow

I have a Vue.js webapp that I am trying to add simple authentication to using AWS Cognito and Amplify Auth. I have my user pool set up with "Authorization code grant" enabled for the OAuth flow. I also have the redirect URL set as https://example.auth.us-east-2.amazoncognito.com/login?response_type=code&client_id=XXXXXXXX&redirect_uri=https://example.com/auth/verify for the hosted UI.

This is what's within the page the hosted UI redirects to:

import { Auth } from "aws-amplify";

export default {
    async created() {
        try {
            await Auth.currentSession();
        } catch {
            console.error("Not authorized");
        }
    }
}

When I sign in the first time through the hosted UI and am redirected, I get an error and am not recognized by Amplify as being authenticated. However if I sign in a second time, there is no error in the console and I have an authenticated session.

I do know that authorization code grant doesn't put the tokens in the URL, but I do see them in localstorage even on the first sign in. I have tried switching to using the "token" OAuth flow but the Amplify docs say the refresh token isn't provided that way and I'd like to not have sessions limited to 1 hour. Any guidance here?

like image 912
Chris B. Avatar asked Feb 28 '20 01:02

Chris B.


People also ask

Does AWS Cognito use OAuth?

In addition to using the Amazon Cognito-specific user APIs to authenticate users, Amazon Cognito user pools also support the OAuth 2.0 authorization framework for authenticating users.

Is Auth0 better than Cognito?

If your costs can scale with Auth0's pricing and you don't need to customise their flows too much, then Auth0 is the way to go. AWS Cognito's generous free tier and tight integration with other AWS services make it a great option if you can deal with sub-par documentation and support.

What is hosted UI in Cognito?

The Amazon Cognito Hosted UI provides you an OAuth 2.0 compliant authorization server. It includes default implementation of end user flows such as registration and authentication. You can also customize user flows, such as the addition of Multi Factor Authentication (MFA), by changing your user pool configuration.


1 Answers

For anyone facing the same problem, this seems to be a known issue.

The workaround is to subscribe to Hub actions and handle it there like

Hub.listen("auth", ({ payload: { event, data } }) => {
  switch (event) {
  case "signIn":
    // signin actions
    Auth.currentSession()
      .then(user => console.log(user)) // redirect to default page
      .error(err => console.log(err))
  case "signOut":
    // signout actions, redirect to '/' etc
  case "customOAuthState":
    // other changes
  }
}

refer to https://github.com/aws-amplify/amplify-js/issues/5133#issuecomment-600759135

like image 106
S.B Avatar answered Oct 11 '22 15:10

S.B