
本文档旨在提供一种在 Spring Security 中实现 JWT(JSON Web Token)刷新令牌机制的最佳实践方案,核心在于限制刷新令牌的使用范围,确保其仅能用于刷新令牌的端点,从而提高系统的安全性,避免刷新令牌被滥用。通过为访问令牌添加特定的权限,并配置 Spring Security 的权限验证规则,可以有效地实现这一目标。
为了限制刷新令牌的使用,我们需要区分访问令牌和刷新令牌,并仅允许访问令牌访问受保护的资源。这可以通过以下步骤实现:
这样,只有持有包含 "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. 注意事项
通过为访问令牌添加特定的权限,并配置 Spring Security 的权限验证规则,可以有效地限制刷新令牌的使用范围,提高系统的安全性。这种方法简单易懂,易于实现,并且不需要存储刷新令牌。
此外,为了进一步提高安全性,可以考虑实现刷新令牌的单次使用机制。这需要将刷新令牌存储在数据库中,并在每次使用后将其删除。虽然这会增加实现的复杂性,但可以有效地防止刷新令牌被滥用。
以上就是限制 JWT 刷新令牌仅用于特定端点的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号