How to redirect users to the last active page before logout after login?

Viewed 859

I am using keycloak-angular for SSO.

https://www.npmjs.com/package/keycloak-angular

And now I want to redirect users to the last active page before logout after login.

How could I implement this?

Does keycloak-angular have some build-in mechanisms for handling this?

2 Answers

Store the path of last active page in a cookie and redirect the user to that page after login using 'Router'

I don't think it has anything to do with keycloak-angular, all you need to use to achieve what you want is Angular Router, Angular ActivatedRoute and localStorage.
First of all your login and logout methods should have the ability to to store and read the last visited route, and you can use localStorage to so just that:

Inside your login service:

  logout() {
    this.route.url.subscribe(url => {
      // read the last visited route and save it to local storage
      localStorage.setItem('last-route-visited', url[0].path)
      // then logout
      this.router.navigate(['/login'])
    })
  }

  login() {
    // read the saved route from local storage
    const lastRouteVisited = localStorage.getItem('last-route-visited')
    // then navigate to it
    this.router.navigate([lastRouteVisited])
  }

Don't forget to add the service as a provider in your component, because otherwise he won't have access to the last visited route.

Inside the component who uses the login/logout service:

@Component({
  ...
  providers: [LoginService]
})

Now you can use the logout from your login/logout service:

  logout() {
    this.LoginService.logout()
  }

Here is the link to a github repo for the full demo

You will also have to adjust the login and logout methods to your own needs, in my example I just saved a simple string representing the saved route to where I want to navigate, but in your case you may need to save complex strings to the local storage, you can use JSON.parse() and JSON.stringify() to do so.

Related