Spring Security资源服务器表单登录后getAuthentication返回null如何解决
问题根因
Spring Security 资源服务器的默认配置会将会话创建策略设置为STATELESS,完全不依赖HTTP Session存储认证上下文。而表单登录的认证逻辑需要依赖Session存储登录成功后的Authentication对象,重定向后的请求才能读取到认证信息。默认无状态配置下,登录成功的认证信息不会写入Session,因此重定向到/login-successful时读取到的Authentication为null,触发未授权错误。
修复方案
在现有HttpSecurity配置中明确指定会话创建策略为IF_REQUIRED即可兼容两种认证方式,修改后的配置代码如下:
public void configure(final HttpSecurity http) throws Exception { http // 新增会话策略配置 .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .authorizeRequests() .antMatchers("/rest/products/add").hasAnyRole("ADMIN") .anyRequest().authenticated() .and().formLogin() .loginPage("/login.jsf").permitAll() .loginProcessingUrl("/login") .defaultSuccessUrl("/login-successful", true) .and().logout().permitAll(); }
需要确保导入对应依赖类:import org.springframework.security.config.http.SessionCreationPolicy;
可选优化
如果需要更清晰的逻辑隔离,可以拆分两套独立的Security配置:
- 给
/rest/**路径的资源配置单独的规则,会话策略设为STATELESS,仅支持Bearer Token认证 - 给网页路径配置单独的规则,会话策略设为
IF_REQUIRED,仅支持表单登录
两套配置通过@Order注解指定优先级,避免规则冲突。
内容的提问来源于stack exchange,提问作者Dmitry
相关产品推荐
相关产品推荐

