CORS: credentials mode is 'include'

JavascriptC#AngularjsCorsasp.net Web-Api2

Javascript Problem Overview


Yes, I know what you are thinking - yet another CORS question, but this time I'm stumped.

So to start off, the actual error message:

> XMLHttpRequest cannot load http://localhost/Foo.API/token. 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:5000'; is therefore not allowed > access. The credentials mode of requests initiated by the > XMLHttpRequest is controlled by the withCredentials attribute.

I'm not sure what is meant by credentials mode is 'include'?

So when I perform the request in postman, I experience no such error:

enter image description here

But when I access the same request through my angularjs web app, I am stumped by this error. Here is my angualrjs request/response. As you'll see the response is OK 200, but I still receive the CORS error:

Fiddler Request and Response:

The following image demonstrates the request and response from web front-end to API

Fiddler

So based on all the other posts I've read online, it seems like I'm doing the right thing, that's why I cannot understand the error. Lastly, here is the code I use within angualrjs (login factory):

enter image description here

CORS Implementation in API - Reference purposes:

Method 1 used:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("*", "*", "*")
        {
            SupportsCredentials = true
        };
        config.EnableCors(cors);
    }
}

Method 2 used:

public void Configuration(IAppBuilder app)
{
    HttpConfiguration config = new HttpConfiguration();
 
    ConfigureOAuth(app);
 
    WebApiConfig.Register(config);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(config);

}

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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'}));

`

Solution 3 - Javascript

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()

Solution 4 - Javascript

If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.

Inside of ConfigureServices

services.AddCors(o => {
    o.AddPolicy("AllowSetOrigins", options =>
    {
        options.WithOrigins("https://localhost:xxxx");
        options.AllowAnyHeader();
        options.AllowAnyMethod();
        options.AllowCredentials();
    });
});
        
services.AddMvc();

Then inside of Configure:

app.UseCors("AllowSetOrigins");
app.UseMvc(routes =>
    {
        // Routing code here
    });

For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned. As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.

Solution 5 - Javascript

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichard BaileyView Question on Stackoverflow
Solution 1 - JavascriptgeekonautView Answer on Stackoverflow
Solution 2 - JavascriptAnkur KediaView Answer on Stackoverflow
Solution 3 - JavascriptPavelView Answer on Stackoverflow
Solution 4 - JavascriptSteven PfeiferView Answer on Stackoverflow
Solution 5 - JavascriptGustavo GarciaView Answer on Stackoverflow