Angular app non stop refresh after login with code and state query string

Angular Code:
appmodule.ts
AuthModule.forRoot({
domain: ‘XXXXXX’,
clientId: ‘XXXXXX’,
authorizationParams: {
redirect_uri: ‘http://localhost:4200
}
}),

app.component.ts
export class AppComponent implements OnInit {
constructor(public auth: AuthService) { }
ngOnInit(): void {
this.auth.loginWithRedirect({
appState: { target: ‘’ }
});
}

I am able to login through auth0, but after login page reloads automatically with new code and state querystring in url.

You should ensure you redirect back to an URL that is not calling loginWithRedirect again, you are causing an infinite loop because you call loginWithRedirect on ngOnInit.

Solutions here:

  • put login behind a button
  • redirect back to a different route, e.g. ‘/callback’ that does not call loginWithRedirect again.
1 Like

Thanks @frederik.prijck . This solution works, but my requirement has no start page, the application needs to load auth0 login page first and then redirect to home page after login.
Is it possible to achieve this scenario with Auth0.

Yes, you need to configure the SDK as follows:

  • set the authorizationParams.redirect_uri to a unprotected route, e.g. window.location.origin + '/callback'
  • ensure the router has a route configured for callback that does not require authentication
  • call loginWithRedirect and configure appState.target to be /, this ensures our SDK redirects back to the home page after the user was authenticated succesful.

The important part is, as mentioned, to redirect back to an unprotected route that does not call loginWithRedirect.

On top of that, you should not call loginWithRedirect when the user is already authenticated.

Even better would be to use our AuthGuard to protect the home URL, but you still need the /callback redirect_uri part.

1 Like

I will try this and come back.
Thanks for the reply @frederik.prijck

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.