Сеанс Spring Security JSESSIONID

В настоящее время я разрабатываю REST API с Spring Boot для внешнего приложения Angular2.

Я использую Spring Security для управления аутентификацией пользователей, но мне нужно сохранить некоторую информацию в сеансе браузера. Проблема в том, что при каждом запросе создается новый JSESSIONID.

Пример:

  1. Аутентификация POST Возвращает Set-Cookie:JSESSIONID=C367245309E4E80606066FDCFBE0EE43 в заголовке ответа. Новый сеанс создается с информацией о пользователе

Авторизация

  1. Защищенный ресурс REST GET: сеанс пуст, а JSESSIONID файл cookie отсутствует в заголовке запроса. Он возвращает Set-Cookie:JSESSIONID=163B28B7AC2042F9EFF1046F9E14A600

Проверка авторизации

Моя конфигурация безопасности Spring:

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

    // Unable x-frame-options from same origin
    httpSecurity.headers().frameOptions().sameOrigin();

    /*
     * the secret key used to signe the JWT token is known exclusively by
     * the server. With Nimbus JOSE implementation, it must be at least 256
     * characters longs.
     */
    String secret = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("secret.key"),
            Charset.defaultCharset());

    httpSecurity.addFilterAfter(jwtTokenAuthenticationFilter("/**", secret), ExceptionTranslationFilter.class)
            .addFilterBefore(new SimpleCORSFilter(), CorsFilter.class)
            /*
             * Exception management is handled by the
             * authenticationEntryPoint (for exceptions related to
             * authentications) and by the AccessDeniedHandler (for
             * exceptions related to access rights)
             */
            .exceptionHandling().authenticationEntryPoint(new SecurityAuthenticationEntryPoint())
            .accessDeniedHandler(new RestAccessDeniedHandler()).and()

            /*
             * anonymous() consider no authentication as being anonymous
             * instead of null in the security context.
             */
            .anonymous().and()
            /* No Http session is used to get the security context */
            //
            .sessionManagement().maximumSessions(1).and().sessionFixation().none()
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and().authorizeRequests()
            /*
             * All access to the authentication service are permitted
             * without authentication (actually as anonymous)
             */
            .antMatchers("/auth/**").permitAll().antMatchers("/css/**").permitAll().antMatchers("/js/**")
            .permitAll().antMatchers("/accueil").permitAll()
            // .antMatchers("/**").permitAll()
            /*
             * All the other requests need an authentication. Role access is
             * done on Methods using annotations like @PreAuthorize
             */
            .anyRequest().authenticated().and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class).csrf()
            .csrfTokenRepository(csrfTokenRepository()).disable();
}

Можете ли вы помочь мне исправить мою проблему с сеансом, пожалуйста?


person user2485349    schedule 18.10.2016    source источник


Ответы (1)


Кажется, это проблема angular2, которая не отправляет cookie; Я установил этот код в своем конструкторе перед вызовом REST API:

 constructor(private _http: Http) {
        let _build = (<any>_http)._backend._browserXHR.build;
        (<any>_http)._backend._browserXHR.build = () => {
            let _xhr = _build();
            _xhr.withCredentials = true;
            return _xhr;
        };
    }

И теперь мой JSESSIONID отправляет каждый запрос.

person user2485349    schedule 18.10.2016
comment
У меня та же проблема, но ваше решение мне не подходит... Не могли бы вы показать больше своего кода, пожалуйста? Нравится исходный код вызова ws или ваш app.module? - person QuentinG; 26.01.2017
comment
Эй, вы добавили: response.setHeader(withCredentials, true); и response.setHeader(Access-Control-Allow-Headers,withCredentials); в вашей конфигурации весенней загрузки (например: CorsFilter)? - person user2485349; 27.01.2017
comment
у меня та же проблема, и я добавил заголовок withCredentials true в моей весенней конфигурации, но я получил результат: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. - person Phan Sinh; 27.03.2017
comment
Ваше решение сработало для меня после большой борьбы. Большое спасибо. - person javafan; 15.08.2017