资源服务器 #
一、资源服务器搭建 #
1.1 添加依赖 #
xml
<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>
1.2 配置类 #
java
@Configuration
@EnableWebSecurity
public class ResourceServerConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorize ->
authorize.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}
1.3 配置文件 #
yaml
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:9000
二、权限控制 #
2.1 基于角色 #
java
@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String admin() {
return "Admin access";
}
@GetMapping("/user")
@PreAuthorize("hasRole('USER')")
public String user() {
return "User access";
}
2.2 自定义权限 #
java
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
三、获取用户信息 #
java
@GetMapping("/me")
public Map<String, Object> me(@AuthenticationPrincipal Jwt jwt) {
Map<String, Object> result = new HashMap<>();
result.put("sub", jwt.getSubject());
result.put("name", jwt.getClaim("name"));
result.put("email", jwt.getClaim("email"));
result.put("roles", jwt.getClaim("roles"));
return result;
}
四、总结 #
| 要点 | 说明 |
|---|---|
| 资源服务器 | 验证令牌访问资源 |
| JWT验证 | 自动验证JWT |
| 权限控制 | @PreAuthorize |
接下来让我们学习 实战案例!
最后更新:2026-03-28