Accessing JWT Token from a Spring Boot Rest Controller

匆匆过客 提交于 2021-01-03 07:06:47

问题


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.


回答1:


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!




回答2:


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;
  }


来源:https://stackoverflow.com/questions/54909509/accessing-jwt-token-from-a-spring-boot-rest-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!