Spring security + session: получает заголовок «Set-Cookie», но не установлен в браузере - PullRequest
0 голосов
/ 01 июля 2019

Я пробую Spring Security & Session с угловым интерфейсом. Я получаю код 200 при попытке войти с таким заголовком ответа:

Set-Cookie: SESSION=NGJlYTkzODQtNTQzMy00NGIxLWEzOWYtYTc2MGNlZWY1OTJm; Path=/; HttpOnly; SameSite=Lax

Но в моем следующем запросе к серверу файл cookie не был автоматически установлен в запросе. И, кстати, я не вижу cookie в инструментах разработчика, поэтому думаю, что он не сохранен.

Я работаю на местном уровне для передней и задней части.

Вот некоторая информация о серверной части:

  • с использованием Spring MongoDb Session @Configuration @EnableMongoHttpSession public class SessionConfig { }

    • Classic Spring Config

` @EnableWebSecurity открытый класс SecurityConfig расширяет WebSecurityConfigurerAdapter { закрытый финал CustomAuthenticationProvider authProvider;

public SecurityConfig(CustomAuthenticationProvider authProvider) {
    this.authProvider = authProvider;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors().and()
        .authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .httpBasic(); //todo csrf
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("http://localhost:4200")); // todo properties by environment
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
    configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

} `

Сессия хорошо сохраняется в mongodb, только идентификатор не сохраняется в браузере. Есть идеи?

редактировать

При настройке observer: "response" в параметрах httpClient я не вижу заголовок Set-Cookie:

"cache-control: no-cache, no-store, max-age=0, must-revalidate,content-type: application/json,expires: 0,pragma: no-cache"

Но в инструменте разработчика у меня есть:

HTTP/1.1 200 Vary: Origin Vary: Access-Control-Request-Method Vary: Access-Control-Request-Headers Access-Control-Allow-Origin: http://localhost:4200 Access-Control-Allow-Credentials: true X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: 0 X-Frame-Options: DENY Set-Cookie: SESSION=YTEwOTNkNjAtZjI4MS00ZmM2LWExYmEtYzA5NzJhMjAyNTJh; Path=/; HttpOnly; SameSite=Lax Content-Type: application/json Transfer-Encoding: chunked Date: Mon, 01 Jul 2019 11:25:08 GMT

Ответы [ 2 ]

0 голосов
/ 01 июля 2019

Создать CORS-фильтр в бэкэнде и добавить его

response.setHeader("Access-Control-Allow-Headers",
                "Date, Content-Type, Accept, X-Requested-With, Authorization, From, X-Auth-Token, Request-Id");
response.setHeader("Access-Control-Expose-Headers", "Set-Cookie");
response.setHeader("Access-Control-Allow-Credentials", "true");
0 голосов
/ 01 июля 2019

Проблема была в угловой стороне!Я добавил перехватчик, добавив параметр withCredentials, и он работает.

@Injectable()
export class XhrInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const xhr = req.clone({
      withCredentials: true
    });
    return next.handle(xhr);
  }
}
...