Spring security session not working when Angular app is running in development (ng serve)

Viewed 43

As the title implies, I have the backend developed using Spring/Spring Security and the frontend is an Angular app.

When I launch angular app using ng serve (http://localhost:4200), spring session is not working. When I request the application to be served from the backend (http://localhost:8080), the spring session is working as expected.

Most relevant spring security configs

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .httpBasic()
        .and()
        .logout().clearAuthentication(true).invalidateHttpSession(true).deleteCookies("JSESSIONID")
        .and()
        .rememberMe().key("uniqueAndSecret").rememberMeParameter("rememberMe").tokenValiditySeconds(Integer.parseInt(rememberMeDuration))
        .and()
        .authorizeHttpRequests().antMatchers(UNPROTECTED_ROUTES).permitAll().anyRequest().authenticated()
        .and()
        .csrf().disable()
        .cors().configurationSource(corsConfigurationSource())
        .and()
        .authenticationManager(authManager(http, userDetailsServiceConfig))
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
    return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();

    configuration.setAllowCredentials(true);
    configuration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name(), HttpMethod.OPTIONS.name()));
    configuration.setAllowedHeaders(Collections.singletonList("*"));
    configuration.setExposedHeaders(Collections.singletonList("*"));
    configuration.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration(
            "/**",
            new CorsConfiguration().applyPermitDefaultValues().combine( configuration)
    );
    return source;
}

And an example of a request from the frontend that does not work (when running from ng serve). I get always 401 (when I call this code I already did a successful authentication)

public vehicleAlimentationByCSV(formData: FormData): Observable<VehicleAlimentationResponseModel> {
    const endPoint = `${this.url}/csv`;

    return this.http
        .post<VehicleAlimentationResponseModel>(
            endPoint,
            formData,
            {
                observe: 'response',
                withCredentials: true
            }
        )
        .pipe(
            map(resp => resp.body!)
        );
}

Maybe a very simple miss configuration. I have searched for an explanation why this is happening but I got nothing.

Thank you for your time!

0 Answers
Related