ChatGPT解决这个技术问题 Extra ChatGPT

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

I have a setup involving

Frontend server (Node.js, domain: localhost:3000) <---> Backend (Django, Ajax, domain: localhost:8000)

Browser <-- webapp <-- Node.js (Serve the app)

Browser (webapp) --> Ajax --> Django(Serve ajax POST requests)

Now, my problem here is with CORS setup which the webapp uses to make Ajax calls to the backend server. In chrome, I keep getting

Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.

doesn't work on firefox either.

My Node.js setup is:

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
};

And in Django I'm using this middleware along with this

The webapp makes requests as such:

$.ajax({
    type: "POST",
    url: 'http://localhost:8000/blah',
    data: {},
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    dataType: 'json',
    success: successHandler
});

So, the request headers that the webapp sends looks like:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json 
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=***; sessionid="***"

And here's the response header:

Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: application/json

Where am I going wrong?!

Edit 1: I've been using chrome --disable-web-security, but now want things to actually work.

Edit 2: Answer:

So, solution for me django-cors-headers config:

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/
)
For me it is localhost:3000 without http, like this: CORS_ORIGIN_WHITELIST = ( 'localhost:3000', )
Do you mean you use develop the frontend and backend in one PC?
how about the frontend and backend in different PC?
@ixaxaar why you say with the http works for you? we all only ` 'localhost:3000'` works.
@244boy yeah the point is not the http, it is the / at the end. I suppose omitting http could work, but I've not really worked on this stuff for some years, so don't really know what works now!

C
Community

This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :

Access-Control-Allow-Origin wildcard subdomains, ports and protocols Cross Origin Resource Sharing with Credentials

Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.


But what if there's more than one domain?
@aroth You can give a list of domains. Related question: stackoverflow.com/questions/1653308/…
@user568109 Could you explain "Besides * is too permissive and would defeat use of credentials."?
What is the "exact domain" if the request comes from mobile device, like it can happen with Cordova?
@Christian kinda old, but if anyone still curious, this problem happens only for applications running on browsers, because this error is thrown by the browser for security reasons. Other clients such as a mobile app, postman or any other backend code using http client to make a request won't have this problem, so you don't have to worry about the origin and the exact domain.
B
BSMP

If you are using CORS middleware and you want to send withCredential boolean true, you can configure CORS like this:

var cors = require('cors');    
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

C
Christoph Hansen

Expanding on @Renaud idea, cors now provides a very easy way of doing this:

From cors official documentation found here:

" origin: Configures the Access-Control-Allow-Origin CORS header. Possible values: Boolean - set origin to true to reflect the request origin, as defined by req.header('Origin'), or set it to false to disable CORS. "

Hence we simply do the following:

const app = express();
const corsConfig = {
    credentials: true,
    origin: true,
};
app.use(cors(corsConfig));

Lastly I think it is worth mentioning that there are use cases where we would want to allow cross origin requests from anyone; for example, when building a public REST API.


I like this answer! especially about the fact that there are use cases where you want to allow all origins (many answers here seem to assume that it is always a bad practice).
B
Bulkan

If you are using express you can use the cors package to allow CORS like so instead of writing your middleware;

var express = require('express')
, cors = require('cors')
, app = express();

app.use(cors());

app.get(function(req,res){ 
  res.send('hello');
});

Ah, now that's more convenient, however, the result's the same :( BTW, I'm using app.use(cors({credentials: true}));
You might want to look into this Django CORS middleware that is tested.
So you have two Django middlewares ? I would only use django-cors-header app. Make sure you add localhost to CORS_ORIGIN_WHITELIST setting and set CORS_ALLOW_CREDENTIALS to True
Yeah man, tried that before to no avail, had CORS_ORIGIN_ALLOW_ALL = True, CORS_ORIGIN_WHITELIST = ( 'localhost' ) and CORS_ALLOW_CREDENTIALS = True I get these headers: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost:3000/ Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE Content-Type: application/json
After reading this documentation: github.com/expressjs/corsuse i using this config: app.use(cors({credentials: true, origin: 'localhost:3001'})); is working for me.
T
Thomas Smyth

try it:

const cors = require('cors')

const corsOptions = {
    origin: 'http://localhost:4200',
    credentials: true,

}
app.use(cors(corsOptions));

S
Squirrl

If you want to allow all origins and keep credentials true, this worked for me:

app.use(cors({
  origin: function(origin, callback){
    return callback(null, true);
  },
  optionsSuccessStatus: 200,
  credentials: true
}));

@TSlegaitis Haha yeah that's why it works for all origins but keeps credentials. I wouldn't recommend it for security but it does work.
R
Renaud

This works for me in development but I can't advise that in production, it's just a different way of getting the job done that hasn't been mentioned yet but probably not the best. Anyway here goes:

You can get the origin from the request, then use that in the response header. Here's how it looks in express:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin') );
  next();
});

I don't know what that would look like with your python setup but that should be easy to translate.


Mozilla Dev Docs expand on the idea of changing the allowed origin to the one from the request. It is suggested to add a 'Vary: Origin' HTTP response header and whitelist allowed domains.
e
eriel marimon

(Edit) The previously recomended add-on is not available any longer, you may try this other one

For development purposes in Chrome, installing this add on will get rid of that specific error:

Access to XMLHttpRequest at 'http://192.168.1.42:8080/sockjs-node/info?t=1546163388687' 
from origin 'http://localhost:8080' has been blocked by CORS policy: 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'. The credentials mode of requests 
initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

After installing, make sure you add your url pattern to the Intercepted URLs by clicking on the AddOn's (CORS, green or red) icon and filling the appropriate textbox. An example URL pattern to add here that will work with http://localhost:8080 would be: *://*


I got it just after installing it, any ideas?
It worked for me. Warning if you have other similar add-ons you have to uninstall it before try this one.
please fix the broken link
Seems like the original add on was removed, I added a new recommendation as an (Edit) at the top
c
connectedMind

Had this problem with angular, using an auth interceptor to edit the header, before the request gets executed. We used an api-token for authentification, so i had credentials enabled. now, it seems it is not neccessary/allowed anymore

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone({
      //withCredentials: true, //not needed anymore
      setHeaders: {
        'Content-Type' : 'application/json',
        'API-TOKEN' : 'xxx'
      },
    });
    
    return next.handle(req);
  }

Besides that, there is no side effects right now.