Spring 安全重新创建 HttpSession

Spring Security recreates HttpSession

我尝试配置 Spring 安全,但遇到一个问题。

这是我的 SessionAuthenticationFilter:

public class SessionAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (nonNull(user)) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(user.getRole());
            Authentication authentication = new UsernamePasswordAuthenticationToken(user.getName(), null, singletonList(authority));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(request, response);
    }

}

这是我的安全配置:

@Configuration
@EnableWebSecurity
@EnableJdbcHttpSession
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public SessionAuthenticationFilter sessionFilter() {
        return new SessionAuthenticationFilter();
    }

    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .csrf().disable()
                .formLogin().disable()
                .cors()
                .and()
                .httpBasic()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(sessionFilter(), SessionManagementFilter.class)
                .authorizeRequests()
                .antMatchers(
                        "/login"
                )
                .permitAll()
                .anyRequest()
                .authenticated();
    }

}

这是我的 IndexController:

@RestController
public class IndexController {

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ResponseEntity<?> index(HttpSession session) {

        System.out.println(session.getId());

        return new ResponseEntity<>(HttpStatus.OK);
    }

}

SessionAuthenticationFilter 里面的 HttpSession 是正确的,但是当我尝试获取这个会话时,我会获取其他会话。为什么?我了解这是创建 Spring 安全性。它是如何固定的?

您的问题可能与此有关:.sessionCreationPolicy(SessionCreationPolicy.STATELESS)

根据 Spring 安全文档,Spring 安全永远不会创建 HttpSession 并且在设置会话创建策略时永远不会使用它来获取 SecurityContextSTATELESS

尝试将策略更改为 SessionCreationPolicy.ALWAYS

Enum SessionCreationPolicy