Spring Security 重新创建 HttpSession

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


这是我的 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"

    }


}


在 SessionAuthenticationFilter 内部 HttpSession 是正确的,但是当我尝试获取此会话时,我将获取其他会话。为什么?我了解这是创建 Spring Security 的。它是如何固定的?


偶然的你
浏览 157回答 1
1回答

qq_遁去的一_1

您的问题可能与此有关:.sessionCreationPolicy(SessionCreationPolicy.STATELESS)根据 Spring Security Docs,Spring Security 永远不会创建一个HttpSession,也永远不会使用它来获取SecurityContext会话创建策略设置为STATELESS.尝试将政策更改为SessionCreationPolicy.ALWAYS请参见 枚举 SessionCreationPolicy
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java