Sma*_*ajl 6 java oauth-2.0 jwt spring-boot
我有一个单独的身份验证服务器和一个资源服务器——都是 Spring Boot 应用程序。我正在使用带有 JWT 令牌的 OAuth2 进行身份验证和授权。
我可以通过访问身份验证服务器来获取令牌:
curl -X POST --user 'client:secret' -d 'grant_type=password&username=john&password=123' http://localhost:9000/auth-server/oauth/token
Run Code Online (Sandbox Code Playgroud)
并通过将令牌附加到请求标头从资源服务器(在不同服务器上运行)获取资源时使用它。
但是,我不清楚的是确定哪个用户登录到资源服务器。
在身份验证服务器中,我可以执行以下操作:
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
Run Code Online (Sandbox Code Playgroud)
并且此端点将根据所使用的令牌为我获取当前用户。如果我尝试在资源服务器中做同样的事情,我只会得到空响应。
我需要在资源服务器中以某种方式获取经过身份验证的用户的 id 以决定是否应该向他返回一些数据(我有一些只能由其所有者访问的资源)。
我怎么能那样做?我认为通过使用 JWT,我不需要共享相同的令牌存储。
如果我的问题不清楚,我可以提供代码示例..我只是想确认我的假设是正确的并且可以实现这种行为 - 这是我第一次尝试 Spring Security。
资源服务器链接到 application.properties 中的 auth 服务器:
security.oauth2.resource.userInfoUri: http://localhost:9000/auth-server/user
Run Code Online (Sandbox Code Playgroud)
这就是我所做的,对于任何对此有疑问的人(此方法使用 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
}
Run Code Online (Sandbox Code Playgroud)
在 application.yml/.properties 中,需要指向 JWK 端点:
spring.security.oauth2.resourceserver.jwt.jwk-set-uri: <JWK_ENDPOINT>
Run Code Online (Sandbox Code Playgroud)
在您的控制器中,您可以使用主体和身份验证。
@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
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以解析 JWT(因为此时,BearerTokenAuthenticationFilter 将验证 JWT - 在过期和其他方面)以读取声明。这仅在您有一个可以轻松使用的声明时才有效。
小智 -1
您的资源服务器不会自动从身份验证服务神奇地获取主体。他们必须受到约束。将身份验证令牌插入标头是正确的方法。但是,资源服务器必须“验证”身份验证令牌。一旦您使用身份验证服务器验证身份验证令牌,主体将被返回。
因此,您的资源服务器需要调用您的身份验证服务器上的“/user”。
这是一个例子。http://technicalrex.com/2015/02/20/stateless-authentication-with-spring-security-and-jwt
| 归档时间: |
|
| 查看次数: |
12290 次 |
| 最近记录: |