Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing JWT Token from a Spring Boot Rest Controller

I am implementing a REST API with Spring Boot and I am securing it with JWT and Oauth 2.

I have no problems with authentication and producing an access token.

When a user makes a request I want to access its JWT token from the controller.

@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<AppUser> getUsers(OAuth2Authentication auth) {
    logger.info("CREDENTIALS:" + auth.getCredentials().toString());
    logger.info("PRINCIPAL:" + auth.getPrincipal().toString());
    logger.info("OAuth2Request:" + auth.getOAuth2Request());
    logger.info("UserAuthentication:" + auth.getUserAuthentication());
    return userService.findAllUsers();
}

I tried something like above but could not reach the token, I only get user name. Is there a way to achieve this in Spring Boot?

Any help would be appreciated.

like image 244
Tartar Avatar asked Feb 27 '19 15:02

Tartar


1 Answers

Tartar,

Is the UI sending the token as header in the request? if that is the case then you can get that value using @RequestHeader annotation in your method

@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<AppUser> getUsers(OAuth2Authentication auth, @RequestHeader (name="Authorization") String token) 

Note: For this example Authorization is the header name that contains the token, this could be a custom header name.

Cheers!

like image 108
Karl Avatar answered Oct 25 '22 17:10

Karl