如何将 JWT 仅应用于我在 Spring Security 6 中创建的端点?
我只希望我的端点具有 JWT 身份验证,其余的应该可供所有人免费访问。我正在使用 Spring Boot 3 和 Spring Security 6。
要将 JWT 身份验证仅应用于 Spring Security 6 中的特定端点,您可以配置安全配置以包含必要的规则。这是您如何实现此目标的示例:
WebSecurityConfigurerAdapter
的配置类:@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/secure/**").authenticated() // Secure endpoints
.anyRequest().permitAll() // Allow access to other endpoints
.and()
.oauth2ResourceServer()
.jwt();
}
}
在上面的例子中,
configure()
方法配置了安全规则。 antMatchers("/api/secure/**").authenticated()
行指定任何以 /api/secure/
开头的端点都需要使用有效的 JWT 令牌进行身份验证。您可以修改此模式以匹配您想要的端点。
anyRequest().permitAll()
行允许访问所有其他端点而无需身份验证。
.oauth2ResourceServer().jwt()
配置使用OAuth 2.0资源服务器和JWT身份验证机制启用JWT身份验证。
根据您的要求自定义配置,例如添加附加规则、定义角色或指定自定义身份验证提供程序。
请记住根据您的特定应用程序需求调整端点模式和访问规则。使用此配置,只有匹配指定模式的端点需要有效的 JWT 令牌才能访问,而其余端点将可供所有人自由访问。