Search code examples
javascriptangularangular-routingangular-routeraws-amplify

Angular router does not react to Cognito redirect?


When we use social login with AWS Cognito, Cognito sends a redirect to the browser to go to the signin redirect URL post signin. The configured URL for that in this case is http://localhost:4200/home/.

When the app receives this redirect, it does go to http://localhost:4200/home/ however the component displayed is still the one for http:localhost:4200/signin/. If I manually refresh the page by selecting the URL and hitting enter, the the home component is displayed.

The router configuration looks like this:

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'signin' },
  { path: 'home', component: HomeComponent, canActivate: [ AuthGuard ] },
  { path: 'signin', component: SigninComponent, canActivate: [ UnauthGuard ] },
  { path: 'signout', component: SignoutComponent, canActivate: [ UnauthGuard ] }
]

So the app always redirects to signin at first. The problem seems to be the double redirect.

Thoughts on how to fix this?

I tried it without the Router redirect. I added a welcome page that is displayed with the '' route. When clicking login on this page, the app still reloads with the signin route initially (Where it leftoff ) and the redirects to the home route, however the signin component is still displayed.

const routes: Routes = [
  { path: '', component: WelcomeComponent, canActivate: [ UnauthGuard ] },
  { path: 'home', component: HomeComponent, canActivate: [ AuthGuard ] },
  { path: 'signin', component: SigninComponent, canActivate: [ UnauthGuard ] },
  { path: 'signout', component: SignoutComponent, canActivate: [ UnauthGuard ] }
]


Update

See Answer. Filed a bug report:

https://github.com/aws-amplify/amplify-js/issues/4988


Solution

  • Figured it out. Even though the user is Authenticated after signing in with Google the first call like this post signing:

        Auth.currentAuthenticatedUser()
          .then((u) => {
            console.log('The user is : ', u)
          }).catch(e=>{console.log("NOT AUTHENTICATED YET")})
      }
    
    

    Logs NOT AUTHENTICATED YET. So the AuthGuard does not allow the user to pass through.

    When the page is refreshed again then Auth.currentAuthenticatedUser() return the user, so the guards direct the application to the correct page.