简体   繁体   中英

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

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?

将最后一个活动页面的路径存储在 cookie 中,并在使用“路由器”登录后将用户重定向到该页面

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM