Chris B.
Chris B.

Reputation: 465

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?

Upvotes: 7

Views: 5114

Answers (1)

S.B
S.B

Reputation: 847

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

Upvotes: 8

Related Questions