我有一个单独的身份验证服务器和一个资源服务器 - 都是 Spring Boot 应用程序。我正在使用带有 JWT token 的 OAuth2 进行身份验证和授权。
我可以通过访问授权服务器来获取 token :
curl -X POST --user 'client:secret' -d 'grant_type=password&username=john&password=123' http://localhost:9000/auth-server/oauth/token
并在通过将 token 附加到请求 header 来从资源服务器(在不同服务器上运行)获取资源时使用它。
但我不清楚的是确定哪个用户登录到资源服务器。
在授权服务器中,我可以做这样的事情:
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
并且此端点将根据使用的 token 为我获取当前用户。但是,如果我尝试在资源服务器中做同样的事情,我只会得到空响应。
我需要以某种方式在资源服务器中获取经过身份验证的用户的 ID,以决定我是否应该将一些数据返回给他(我有一些资源只能由其所有者访问)。
我该怎么做?我认为通过使用 JWT,我不需要共享相同的 token 存储。
如果我的问题不清楚,我可以提供代码示例。我只是想确认我的假设是正确的,并且可以实现这种行为 - 这是我第一次尝试使用 spring 安全性。
资源服务器链接到application.properties中的auth服务器:
security.oauth2.resource.userInfoUri: http://localhost:9000/auth-server/user
最佳答案
这就是我为遇到此问题的任何人所做的(此方法使用 JWK 来验证 JWT)。
您首先需要设置一个扩展 WebSecurityConfigurerAdapter.class 的配置 bean。在 HttpSecurity 对象中,您可以使用 oauth2ResourceServer.jet() 方法,这非常好。它将为传入请求查找 JWT,并为传入请求设置 Principal 对象(以及其他对象)。它应该看起来像这样:
@Configuration
@EnableWebSecurity(debug = true) //optional - helps with debugging your security filters.
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.antMatcher("/cars/**")
.oauth2ResourceServer().jwt(); // validates the jwt token and also sets the authentication and principal
}
在application.yml/.properties中,需要指向JWK端点:
spring.security.oauth2.resourceserver.jwt.jwk-set-uri: <JWK_ENDPOINT>
在您的 Controller 中,您可以获取委托(delegate)人和身份验证。
@RequestMapping(method = RequestMethod.GET, value = "/cars/{id}")
@ResponseBody
public Car getCar(@PathVariable("id") String id, Principal principal, Authentication auth) {
return new Car(id, "Ford", Color.BLUE, new Owner(principal.getName().toString(), 90120)); //the principal's name is a GUID
}
或者,您可以解析 JWT(因为在这一点上,BearerTokenAuthenticationFilter 将在到期和其他方面验证 JWT)以读取声明。这仅在您有自己喜欢使用的声明时才有效。
关于java - 从 JWT token 获取 Spring Boot 资源服务器中的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38976426/