1

Я пытаюсь настроить 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);
    }

}

Это мой SecurityConfig:

@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 Ыусгкшен. Как это исправить?

1 ответ 1

1

На самом деле, как оказалось, оно работает верно, просто Spring Security каждый раз меняет id сессии для безопасности, а данные в ней остаются не изменными. Если мы не хотим менять этот id, то вместо SessionCreationPolicy.STATELESS нужно использовать SessionCreationPolicy.ALWAYS.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.