
本文档旨在提供一种在 Spring Security 中实现 JWT(JSON Web Token)刷新令牌机制的最佳实践方案,核心在于限制刷新令牌的使用范围,确保其仅能用于刷新令牌的端点,从而提高系统的安全性,避免刷新令牌被滥用。通过为访问令牌添加特定的权限,并配置 Spring Security 的权限验证规则,可以有效地实现这一目标。
解决方案概述
为了限制刷新令牌的使用,我们需要区分访问令牌和刷新令牌,并仅允许访问令牌访问受保护的资源。这可以通过以下步骤实现:
- 为访问令牌添加特定权限: 在生成访问令牌时,为其添加一个特定的权限,例如 "access"。
- 配置 Spring Security: 配置 Spring Security,要求所有受保护的端点都必须具有 "access" 权限。
- 刷新令牌不包含 "access" 权限: 刷新令牌只包含刷新令牌所需的权限,例如 "REFRESH_TOKEN",而不包含 "access" 权限。
这样,只有持有包含 "access" 权限的访问令牌的用户才能访问受保护的资源,而持有刷新令牌的用户只能访问刷新令牌的端点。
代码示例
以下代码示例展示了如何在 Spring Security 中实现上述方案。
1. 修改 JwtTokenService 类:
在 JwtTokenService 类中,修改 generateAccessToken 方法,添加 "access" 权限。
@Service
@RequiredArgsConstructor
public class JwtTokenServiceImpl implements JwtTokenService {
private final JwtEncoder jwtEncoder;
@Override
public String generateAccessToken(User user) {
Instant now = Instant.now();
String scope = user.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
String accessScope = scope.concat(" access"); // 添加 "access" 权限
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plus(2, ChronoUnit.MINUTES))
.subject(user.getUsername())
.claim("roles", accessScope) // 使用 "roles" 作为权限声明名称
.build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
@Override
public String generateRefreshToken(User user) {
Instant now = Instant.now();
String scope = "ROLE_REFRESH_TOKEN";
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plus(10, ChronoUnit.MINUTES))
.subject(user.getUsername())
.claim("scope", scope)
.build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
@Override
public String parseToken(String token) {
try {
SignedJWT decodedJWT = SignedJWT.parse(token);
return decodedJWT.getJWTClaimsSet().getSubject();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}2. 修改 WebSecurityConfig 类:
在 WebSecurityConfig 类中,配置 Spring Security,要求所有受保护的端点都必须具有 "ROLE_access" 权限。
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
public class WebSecurityConfig {
@Value("${app.chat.jwt.public.key}")
private RSAPublicKey publicKey;
@Value("${app.chat.jwt.private.key}")
private RSAPrivateKey privateKey;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.exceptionHandling(
exceptions ->
exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler()));
http.authorizeHttpRequests()
.requestMatchers("/auth/sign-in").permitAll()
.requestMatchers("/auth/sign-up").permitAll()
.requestMatchers("/auth/token/refresh").permitAll() // 允许刷新令牌端点无需 "ROLE_access" 权限
.anyRequest().hasAuthority("ROLE_access") // 需要 "ROLE_access" 权限才能访问其他端点
.and()
.httpBasic(Customizer.withDefaults())
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
@SneakyThrows
@Bean
public JwtEncoder jwtEncoder() {
var jwk = new RSAKey.Builder(publicKey).privateKey(privateKey).build();
var jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
return new NimbusJwtEncoder(jwks);
}
@SneakyThrows
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(publicKey).build();
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
var jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles"); // 设置权限声明名称
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
var jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}3. 注意事项
- 权限声明名称: 确保在 JwtTokenService 类和 WebSecurityConfig 类中使用相同的权限声明名称。在上面的示例中,我们都使用了 "roles"。
- 权限前缀: 在 JwtAuthenticationConverter 中设置了权限前缀 "ROLE_"。这意味着在 hasAuthority 方法中使用的权限名称必须以 "ROLE_" 开头。
- 刷新令牌端点: 确保允许刷新令牌端点无需 "ROLE_access" 权限,否则刷新令牌将无法访问该端点。
- CORS 配置: CORS 配置需要根据实际情况进行调整,示例中允许所有来源,所有header和所有method,生产环境需要进行更严格的限制。
总结
通过为访问令牌添加特定的权限,并配置 Spring Security 的权限验证规则,可以有效地限制刷新令牌的使用范围,提高系统的安全性。这种方法简单易懂,易于实现,并且不需要存储刷新令牌。
此外,为了进一步提高安全性,可以考虑实现刷新令牌的单次使用机制。这需要将刷新令牌存储在数据库中,并在每次使用后将其删除。虽然这会增加实现的复杂性,但可以有效地防止刷新令牌被滥用。










