14.7、资源服务器配置
分类: Spring Cloud Security
资源服务器配置
资源服务器是提供受保护资源的服务。本节将学习资源服务器配置。
本节将学习:资源服务器设置、令牌解析、权限验证,以及端点保护。
资源服务器设置
依赖添加
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
配置文件
spring: security: oauth2: resourceserver: jwt: issuer-uri: http://auth-server jwk-set-uri: http://auth-server/.well-known/jwks.json
安全配置
@Configuration @EnableWebSecurity public class ResourceServerConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/public/**").permitAll() .requestMatchers("/api/**").authenticated() .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt.decoder(jwtDecoder())) ); return http.build(); } @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withJwkSetUri("http://auth-server/.well-known/jwks.json").build(); } }
令牌解析
JWT 解码器
@Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); }
自定义解码器
@Bean public JwtDecoder jwtDecoder() { NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); decoder.setJwtValidator(jwtValidator()); return decoder; } @Bean public JwtValidator jwtValidator() { return new DelegatingJwtValidator( new JwtTimestampValidator(), new JwtIssuerValidator(issuerUri) ); }
令牌提取
@Component public class TokenExtractor { public String extractToken(HttpServletRequest request) { String authHeader = request.getHeader("Authorization"); if (authHeader != null && authHeader.startsWith("Bearer ")) { return authHeader.substring(7); } return null; } }
权限验证
方法级安全
@Configuration @EnableMethodSecurity public class MethodSecurityConfig { // 配置 } @RestController public class UserController { @GetMapping("/api/users/{id}") @PreAuthorize("hasRole('USER')") public User getUser(@PathVariable Long id) { return userService.getUser(id); } @DeleteMapping("/api/users/{id}") @PreAuthorize("hasRole('ADMIN')") public void deleteUser(@PathVariable Long id) { userService.deleteUser(id); } }
自定义权限验证
@Component public class CustomPermissionEvaluator implements PermissionEvaluator { @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { // 自定义权限验证逻辑 return true; } @Override public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { // 自定义权限验证逻辑 return true; } }
端点保护
端点配置
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/actuator/health").permitAll() .requestMatchers("/actuator/**").hasRole("ADMIN") .requestMatchers("/api/public/**").permitAll() .requestMatchers("/api/admin/**").hasRole("ADMIN") .requestMatchers("/api/**").authenticated() .anyRequest().denyAll() ) .oauth2ResourceServer(oauth2 -> oauth2.jwt()); return http.build(); } }
路径匹配
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers(HttpMethod.GET, "/api/users/**").hasAnyRole("USER", "ADMIN") .requestMatchers(HttpMethod.POST, "/api/users/**").hasRole("ADMIN") .requestMatchers("/api/orders/**").authenticated() .anyRequest().permitAll() ) .oauth2ResourceServer(oauth2 -> oauth2.jwt()); return http.build(); }
官方资源
- Spring Security OAuth2 Resource Server:https://spring.io/guides/tutorials/spring-boot-oauth2/
- Spring Security 官方文档:https://spring.io/projects/spring-security
本节小结
在本节中,我们学习了:
第一个是资源服务器设置。 如何配置资源服务器。
第二个是令牌解析。 如何解析和验证 JWT 令牌。
第三个是权限验证。 如何验证用户权限。
第四个是端点保护。 如何保护 API 端点。
这就是资源服务器配置。正确配置资源服务器可以保护微服务的资源。
在下一节,我们将学习 Spring Cloud Security 最佳实践。