spring boot 如何实现 动态 实现API Key鉴权
时间: 2024-01-29 12:03:24 浏览: 243
spring boot 配置动态刷新实现详解
如果你需要在Spring Boot应用中实现动态的API Key鉴权,可以按照以下步骤进行操作:
1.创建一个API Key管理器,用于动态管理和授权API Key。例如,可以实现一个`ApiKeyManager`:
```java
@Component
public class ApiKeyManager {
private final Map<String, ApiKey> apiKeys = new ConcurrentHashMap<>();
public void addApiKey(ApiKey apiKey) {
this.apiKeys.put(apiKey.getKey(), apiKey);
}
public boolean containsApiKey(String key) {
return this.apiKeys.containsKey(key);
}
public boolean isValidApiKey(String key) {
ApiKey apiKey = this.apiKeys.get(key);
return apiKey != null && apiKey.isEnabled() && apiKey.getExpiresAt().isAfter(LocalDateTime.now());
}
}
```
2.创建一个`ApiKey`类,用于存储API Key的信息,例如:
```java
public class ApiKey {
private String key;
private LocalDateTime expiresAt;
private boolean enabled;
// getter and setter methods
}
```
3.在Spring Boot应用中添加Spring Security依赖,并创建一个实现`WebSecurityConfigurerAdapter`的配置类,例如:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final ApiKeyManager apiKeyManager;
public SecurityConfig(ApiKeyManager apiKeyManager) {
this.apiKeyManager = apiKeyManager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").hasAuthority("API_KEY")
.anyRequest().authenticated()
.and()
.addFilterBefore(new ApiKeyAuthenticationFilter(apiKeyManager), UsernamePasswordAuthenticationFilter.class);
}
}
```
4.实现一个自定义的`AuthenticationFilter`,用于API Key的验证。例如,可以实现一个`ApiKeyAuthenticationFilter`:
```java
public class ApiKeyAuthenticationFilter extends OncePerRequestFilter {
private final ApiKeyManager apiKeyManager;
public ApiKeyAuthenticationFilter(ApiKeyManager apiKeyManager) {
this.apiKeyManager = apiKeyManager;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String apiKey = request.getHeader("X-API-KEY");
if (apiKey != null && apiKeyManager.isValidApiKey(apiKey)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(null, null, Collections.singleton(new SimpleGrantedAuthority("API_KEY")));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
}
```
5.在应用启动时,将API Key添加到`ApiKeyManager`中,例如:
```java
@Component
public class ApiKeyInitializer implements CommandLineRunner {
private final ApiKeyManager apiKeyManager;
public ApiKeyInitializer(ApiKeyManager apiKeyManager) {
this.apiKeyManager = apiKeyManager;
}
@Override
public void run(String... args) throws Exception {
ApiKey apiKey = new ApiKey();
apiKey.setKey("your-api-key");
apiKey.setExpiresAt(LocalDateTime.now().plusDays(7));
apiKey.setEnabled(true);
apiKeyManager.addApiKey(apiKey);
}
}
```
这样,就可以在Spring Boot应用中实现动态的API Key鉴权了。通过`ApiKeyManager`动态管理和授权API Key,可以实现更灵活和安全的API鉴权。
阅读全文