CORS: credentials mode is 'include'

193,655

Solution 1

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

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

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

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

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!

Share:
193,655
Richard Bailey
Author by

Richard Bailey

I have over 17 years of experience working in software development / architecture. Currently, I work as a software architect for Kohde.io, improving products and services for our customers by using advanced analytics, S.O.L.I.D principles, creating and maintaining software, and on-boarding compelling new data sets. Competencies: C#, Architectural Patterns, S.O.L.I.D, SQL, LINQ, Rx, MongoDb, Micro-services, REST, Angular, Architecture, TypeScript

Updated on August 24, 2022

Comments

  • Richard Bailey
    Richard Bailey over 1 year

    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);
    
    }
    
  • Ziggler
    Ziggler about 6 years
    I am working on Angular 5 application with TypeScript. I need to give withCredentials as true else I will get Authorization Failed exception. How to solve this withCredentials:true
  • Pavel
    Pavel about 6 years
    @Ziggler I had the same situation. Are you find solutions?
  • Pavel
    Pavel about 6 years
    @Ziggler I fined solution see my answer.
  • mruanova
    mruanova almost 6 years
    I am still getting this error when using WithCredentials=TRUE and Access-Control-Allow-Origin=['localhost:4200'], and I am NOT using star * so the error message makes no sense anymore. ERROR MESSAGE: "Response to preflight request doesn't pass access control check: 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 'localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute."
  • geekonaut
    geekonaut almost 6 years
    @mruanova are you sure the Access-Control-Allow-Origin header is correctly set in the request? It sounds like something gets sent with a wildcard somewhere
  • mruanova
    mruanova almost 6 years
    fixed it by removing Access-Control-Allow-Origin entirely from the request, thanks
  • Alexis.Rolland
    Alexis.Rolland almost 5 years
    On my side the request triggering the error is sent by the hot reload feature of webpack. Do you know where to change withCredentials to false? thanks
  • therightdoctors
    therightdoctors almost 5 years
    when i use WithCredentials=true, then I'm facing error in angular 5. Error Message: "Response to preflight request doesn't pass access control check: 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 'localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute."