简体   繁体   中英

Storing a JWT token

I am using JWT for authentication. Now i want to store this token which is being generated in one class, so that any other class can use it until the session expires. What is the best way to do it. My application is in spring boot. Adding more. I am making a client which hits a rest webservice with the credentials to get the token. Now i need to store this token somewhere so that further rest requests can use it. Is it fine to store the token in httpSession and retrieve it further.

Usually is not a good idea to store a JWT token, since it should contain all the information to identify and authorize a service user without hit the DB/persistence layer.

But maybe there are situations that require to persist it among user data. In this case you can store it in a table/collection and retrieve it while authenticating the user.

If you are using Spring + Spring Security, you can then populate a token field in a custom User implementation.

You can retrieve user data this way:

CustomUser userDetails = (CustomUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

It is not preferred to store a JWT token in order to protect it from CSRF.

But if you want to persist or use it anyways, one way in spring boot is you can just include the @RequestHeader parameter in any rest request with the value as "Authorization" and then you can just fetch out the jwt token from it and can use it as per your functionality :

@GetMapping("/abc")
public ResponseEntity<String> getToken(
    @RequestHeader(value="Authorization")  String authorizationHeader){
    String jwt = authorizationHeader.substring(7);
    //your functionality
    return ResponseEntity.ok("JWT Token successfully retrieved");
}

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