Tartar
Tartar

Reputation: 5452

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.

Upvotes: 24

Views: 64933

Answers (3)

Jo&#227;o Pedro Schmitt
Jo&#227;o Pedro Schmitt

Reputation: 1488

I have use the following approach on Spring Security 6:

@RestController
@RequestMapping(path = "/api/v1/")
public class ApiController {

  public ApiResponse search(final JwtAuthenticationToken auth, @RequestBody final ApiRequest request) throws Exception {
    // ...
  }

}

Upvotes: 4

Karl
Karl

Reputation: 906

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!

Upvotes: 61

Abhijay
Abhijay

Reputation: 328

The answer provided by Karl should solve your issue.

In addition to that answer, you can use the following method and access the token anywhere in the code

public static String getToken() {
    String token = null;
    var authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
      token = ((OAuth2AuthenticationDetails) authentication.getDetails()).getTokenValue();
    }
    return token;
  }

Upvotes: 23

Related Questions