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

Spring配置:如何为移动端API请求禁用Session创建?

解决方案:为REST接口单独配置无状态会话策略

你可以通过Spring Security的多HttpSecurity配置来实现Web端保留会话、REST接口无状态的需求,核心思路是为不同路径的请求分别定义安全规则,互不干扰。

具体实现步骤

在Spring Boot 2.5+版本中,我们不再使用WebSecurityConfigurerAdapter,而是通过注册多个SecurityFilterChain Bean来实现多规则配置:

  1. 优先配置REST接口的无状态规则
    针对你的REST接口路径(比如/api/**),单独设置会话创建策略为STATELESS,同时配置JWT相关的认证逻辑:
@Bean
@Order(1) // 优先级更高,先匹配REST路径
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
    http
        .antMatcher("/api/**") // 匹配所有REST接口路径
        .authorizeRequests(auth -> auth
            .anyRequest().authenticated()
        )
        .sessionManagement(session -> session
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 禁止创建会话
        )
        .oauth2ResourceServer(oauth2 -> oauth2
            .jwt(jwt -> jwt
                .jwtAuthenticationConverter(new JwtAuthenticationConverter()) // 自定义JWT转换逻辑
            )
        );
    return http.build();
}
  1. 配置Web端的默认会话规则
    针对Web端的其他路径(比如/**),保持默认的会话创建策略,沿用原有Web端的认证方式(比如表单登录):
@Bean
@Order(2) // 优先级低于REST配置,作为兜底规则
public SecurityFilterChain webSecurityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeRequests(auth -> auth
            .antMatchers("/login", "/register").permitAll()
            .anyRequest().authenticated()
        )
        .formLogin(form -> form
            .loginPage("/login")
            .permitAll()
        )
        .logout(logout -> logout
            .permitAll()
        );
    // 不指定sessionCreationPolicy,默认使用IF_REQUIRED,按需创建会话
    return http.build();
}

关键说明

  • @Order注解用来定义配置的优先级,数值越小优先级越高。REST接口的配置路径更具体,需要优先匹配,避免被Web端的兜底规则拦截。
  • 针对/api/**的配置明确设置SessionCreationPolicy.STATELESS,Spring Security不会为这些请求创建或使用任何会话,完全依赖JWT令牌完成认证。
  • Web端的配置保持默认会话策略,正常支持用户登录后的会话管理,不会影响原有Web功能的运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:00:02