简体   繁体   中英

Logout springboot jwt

I want make a logout service with controller. I try the next code:

    @GetMapping("/logout")
    public String getLogoutPage(HttpServletRequest request, HttpServletResponse response){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            new SecurityContextLogoutHandler().logout(request, response, authentication);

        return "redirect:/login";
    }

I am actually do test with postman

the next url request authentication ("/example") but when do a logout i still can go to this url with the same token and that's not right.

You can't really log out a JWT token, or not as you would with an opaque token. What makes a JWT valid is the correctness of its signature with the public certificate used to control it and its expiration time. As long as those two conditions are met, the token will be valid. A traditional logout from a JWT based system usually consists of simply removing the token on the client-side.

In case of a security breach, you can rotate the keys used to generate JWTs, but that would log out everyone in the system and is not possible as a per-user strategy.

If you want to handle it on the server-side, you could create a deny list of JWT, add the token you want to log out, and check on every request if the token is in the list. Just be careful on how you implement this to avoid a major overhead in your system (store the expiration time with the denied token and have a job cleaning it regularly).

If your system is distributed with one authentification authority, and multiple different consumers that would only "fix" the logout locally if not properly done. Which means trouble at one point or another. You should also take that in consideration

A good set of rules to work with JWT are:

  1. Don't store them in any kind of place where you can't easily remove them and effectively make a client-side logout.
  2. Have a short expiration time and refresh them often.
  3. Rotate the keys used to generate JWTs every so often depending on your security needs
  4. Have a contingency plan to deal with some use case that pure JWT can't handle: password change, immediately blocking a user...

If those security tradeoffs are something you can't work with, you should consider moving to opaque tokens which can easily be revoked without breaking the model.

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