CORS: credentials mode is 'include'
Customizing CORS for Angular 5 and Spring Security (Cookie base solution)
On the Angular side required adding option flag withCredentials: true
for Cookie transport:
constructor(public http: HttpClient) {
}
public get(url: string = ''): Observable<any> {
return this.http.get(url, { withCredentials: true });
}
On Java server-side required adding CorsConfigurationSource
for configuration CORS policy:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// This Origin header you can see that in Network tab
configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.setAllowedHeaders(Arrays.asList("content-type"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
Method configure(HttpSecurity http)
by default will use corsConfigurationSource
for http.cors()
The issue stems from your Angular code:
When withCredentials
is set to true, it is trying to send credentials or cookies along with the request. As that means another origin is potentially trying to do authenticated requests, the wildcard ("*") is not permitted as the "Access-Control-Allow-Origin" header.
You would have to explicitly respond with the origin that made the request in the "Access-Control-Allow-Origin" header to make this work.
I would recommend to explicitly whitelist the origins that you want to allow to make authenticated requests, because simply responding with the origin from the request means that any given website can make authenticated calls to your backend if the user happens to have a valid session.
I explain this stuff in this article I wrote a while back.
So you can either set withCredentials
to false or implement an origin whitelist and respond to CORS requests with a valid origin whenever credentials are involved
If you are using CORS middleware and you want to send withCredentials
boolean true, you can configure CORS like this:
var cors = require('cors');
app.use(cors({credentials: true, origin: 'http://localhost:5000'}));
`