You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用OAuth2+JWT保护Spring Boot 2.0.0.M7 WebFlux函数式REST API

用OAuth2 + JWT保护Spring Boot 2.0.0.M7 WebFlux函数式API

针对你当前的Spring Boot 2.0.0.M7 + WebFlux函数式API场景,咱们可以通过@EnableWebFluxSecurity配置OAuth2资源服务器,用JWT验证来保护/api/v1/book端点。下面是一步步的实现方案:

1. 添加必要依赖

首先确保项目中包含Spring Security和OAuth2资源服务器的核心依赖,以Maven为例,在pom.xml中添加:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-jose</artifactId>
</dependency>

这些依赖是Spring Boot 2.0 M7版本支持JWT资源服务器的基础包。

2. 编写WebFlux Security配置类

创建一个安全配置类,用@EnableWebFluxSecurity注解,定义SecurityWebFilterChain来指定安全规则和JWT验证逻辑:

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
                // REST API场景下关闭CSRF防护
                .csrf().disable()
                // 配置请求授权规则
                .authorizeExchange(exchanges -> exchanges
                        // 放行根路径(API文档)和actuator端点
                        .pathMatchers("/", "/actuator/**").permitAll()
                        // 保护/api/v1/book下的所有端点,需认证
                        .pathMatchers("/api/v1/book/**").authenticated()
                        // 其他请求默认需要认证
                        .anyExchange().authenticated()
                )
                // 配置OAuth2资源服务器,启用JWT验证
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> jwt
                                .jwtDecoder(jwtDecoder())
                        )
                )
                .build();
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        // 场景1:对接第三方授权服务器(如Auth0、Okta),用JWK集合验证
        // return NimbusJwtDecoder.withJwkSetUri("https://your-auth-server/.well-known/jwks.json").build();

        // 场景2:本地对称密钥签名的JWT,用密钥直接验证
        SecretKey secretKey = Keys.hmacShaKeyFor("your-32-char-or-longer-secret-key-here".getBytes());
        return NimbusJwtDecoder.withSecretKey(secretKey).build();
    }
}

关键说明:

  • 选择对应场景的JwtDecoder:如果用第三方授权服务器生成JWT,用JWK Set URI;如果是自己生成的对称密钥签名JWT,用本地密钥。
  • 安全规则明确区分了公开端点和需要保护的端点,和你现有路由的路径完全匹配。

3. 可选:通过配置文件简化JWT配置

你也可以把JWT验证的配置放到application.yml中,省去代码里手动创建JwtDecoder的步骤:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          # 对接第三方授权服务器时配置JWK地址
          jwk-set-uri: https://your-auth-server/.well-known/jwks.json
          # 本地对称密钥场景下配置密钥
          # secret: your-32-char-or-longer-secret-key-here

4. 验证配置效果

完成配置后:

  • 访问/api/v1/book的GET/POST请求,必须在请求头携带Authorization: Bearer <你的JWT令牌>才能正常访问
  • 根路径/和/actuator仍然保持公开访问,不需要认证

额外扩展(可选)

如果需要更细粒度的权限控制(比如基于角色访问),可以在授权规则中添加角色校验,同时确保JWT中包含对应的权限声明:

// 在authorizeExchange中修改规则
.pathMatchers("/api/v1/book/**").hasAuthority("SCOPE_book:write")

内容的提问来源于stack exchange,提问作者Query

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:19:57