使用spring security 6根据Authorization请求头去redis获取DefaultOAuth2AccessToken然后进行token的权限验证
时间: 2024-09-07 19:03:16 浏览: 129
在Spring Security 6中,你可以利用其内置的OAuth2模块来处理基于Authorization Header的Token验证,同时结合Redis作为令牌存储。这里是一个概述步骤:
1. **添加依赖**:
首先,在你的项目中添加Spring Security OAuth2和Spring Data Redis的相关依赖。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client-jwt</artifactId>
</dependency>
```
2. **配置OAuth2客户端**:
创建一个OAuth2客户端并在`application.yml`或`application.properties`中配置,包括Redis的连接信息。
```yaml
spring:
data:
redis:
host: localhost
port: 6379
security:
oauth2:
client:
registration:
my-client-id:
provider: jwt
secret: your-secret
clientName: MyClient
authorizationGrantType: PASSWORD
tokenUri: /token
scopes:
- read
- write
resource:
serverUrl: http://localhost:8080/api
```
3. **JWT Token生成和验证**:
使用`@EnableAuthorizationServer`注解启用授权服务器,并创建一个自定义的TokenEnhancer,从Redis获取默认的OAuth2 `DefaultOAuth2AccessToken`。
```java
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private AuthenticationManager authenticationManager;
// ...
@Override
public void configure(ClientDetailsServiceRegistry registry) throws Exception {
// ...注册你的客户端细节
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(
accessTokenConverter(), // 自定义转换器
new CustomTokenEnhancer(tokenStore) // 获取Redis中的Token
));
endpoints.tokenStore(tokenStore)
.tokenEnhancer(tokenEnhancerChain);
}
//...
}
```
4. **CustomTokenEnhancer** 类:
实现`TokenEnhancer`接口,从Redis获取`DefaultOAuth2AccessToken`并附加上额外的信息。
```java
@Service
public class CustomTokenEnhancer implements TokenEnhancer {
private final TokenStore tokenStore;
public CustomTokenEnhancer(TokenStore tokenStore) {
this.tokenStore = tokenStore;
}
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
if (accessToken instanceof DefaultOAuth2AccessToken) {
DefaultOAuth2AccessToken enhanced = (DefaultOAuth2AccessToken) accessToken;
String key = getAccessTokenKey(authentication);
EnhancedClientDetails clientDetails = (EnhancedClientDetails) authentication.getUserAuthentication().getPrincipal();
// 从Redis中获取用户权限信息
List<String> scopes = tokenStore.loadScopes(key);
enhanced.setAdditionalInformation("scopes", scopes);
return enhanced;
}
return accessToken;
}
private String getAccessTokenKey(OAuth2Authentication authentication) {
// 根据Authorization Header中的Bearer Token获取key
String authHeader = authentication.getOAuth2Request().getRequestHeaders().get("Authorization");
// 解析key...
}
}
```
5. **权限验证**:
当你收到带有Authorization Header的请求时,Spring Security会自动检查Token是否经过授权。在需要保护的控制器方法上,使用`@PreAuthorize`注解进行权限验证。
```java
@RestController
@RequestMapping("/api")
public class ProtectedController {
@GetMapping("/protected")
@PreAuthorize("#oauth2.hasScope('read')")
public ResponseEntity<String> protectedResource() {
// 如果Token具有"read"权限,返回资源,否则返回错误
// ...
}
}
```
阅读全文
相关推荐


















