从 Spring Boot Rest Controller 访问 JWT 令牌 [英] Accessing JWT Token from a Spring Boot Rest Controller

查看:48
本文介绍了从 Spring Boot Rest Controller 访问 JWT 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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?

任何帮助将不胜感激.

推荐答案

鞑靼,

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 Controller 访问 JWT 令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆