I developed BE with Spring-Boot and for the CSRF setup I followed the documentation of Spring. this is the config of SecurityFilterChain:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(corsSetting -> corsSetting.configurationSource(corsConfigurationFilter()))
.csrf(this::httpCsrfConfiguration)
.addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class)
.authorizeHttpRequests(auth -> auth.requestMatchers(AUTH_LIST)
.permitAll()
.requestMatchers("/reparti/nuovo", "/impiegati/aggiungi", "/impiegati/dimissione")
.hasAuthority("ADMIN")
.requestMatchers("/reparti/**", "/impiegati/**", "pazienti/**", "ricoveri/**")
.authenticated()
.anyRequest()
.authenticated())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.ALWAYS))
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.httpBasic(withDefaults());
return http.build();
}
private void httpCsrfConfiguration(CsrfConfigurer<HttpSecurity> csrf) {
csrf.ignoringRequestMatchers("/register", "/login")
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler());
}
private CorsConfigurationSource corsConfigurationFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedMethods(
List.of(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(), HttpMethod.DELETE.name(),
HttpMethod.OPTIONS.name()));
corsConfiguration.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
corsConfiguration.setAllowedHeaders(
List.of(HttpHeaders.CONTENT_TYPE, HttpHeaders.AUTHORIZATION, HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,
HttpHeaders.ACCEPT, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS,
HttpHeaders.COOKIE, HttpHeaders.SET_COOKIE, "X-Requested-With", "X-XSRF-TOKEN", "XSRF-TOKEN"));
corsConfiguration.setExposedHeaders(
List.of(HttpHeaders.ORIGIN, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT, HttpHeaders.AUTHORIZATION,
HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, HttpHeaders.COOKIE,
HttpHeaders.SET_COOKIE));
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return urlBasedCorsConfigurationSource;
}
In the ‘Set-Cooke’ attribute of response headers the token is declared with name ‘XSRF-TOKEN’, but not in the cookie of browser. Why this behavior?
New contributor
Pietro Salvatore is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.