问题描述
我正在使用Spring Boot实现REST API,并通过JWT和Oauth 2保护它.
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.
当用户发出请求时,我想从控制器访问其JWT令牌.
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();
}
我尝试了类似上述操作,但无法访问令牌,我仅获得用户名.有没有办法在Spring Boot中实现这一目标?
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?
任何帮助将不胜感激.
推荐答案
塔尔(Tartar)
UI是否在请求中将令牌作为标头发送?如果是这种情况,则可以在方法中使用@RequestHeader
批注获取该值
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)
注意:对于本示例,Authorization
是包含令牌的标头名称,这可以是自定义标头名称.
Note: For this example Authorization
is the header name that contains the token, this could be a custom header name.
干杯!
这篇关于从Spring Boot Rest控制器访问JWT令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!