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

365👍

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 :

  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
  2. 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.

97👍

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

65👍

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.

21👍

try it:

const cors = require('cors')

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

}
app.use(cors(corsOptions));

18👍

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

15👍

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

9👍

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.

👤Renaud

4👍

(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: *://*

3👍

Though we have many solutions regarding the cors origin, I think I may add some missing part. Generally using cors middlware in node.js serves maximum purpose like different http methods (get, post, put, delete).

But there are use cases like sending cookie response, we need to enable credentials as true inside the cors middleware Or we can’t set cookie. Also there are use cases to give access to all the origin. in that case, we should use,

{credentials: true, origin: true}

For specific origin, we need to specify the origin name,

{credential: true, origin: "http://localhost:3000"}

For multiple origins,

{credential: true, origin: ["http://localhost:3000", "http://localhost:3001" ]}

In some cases we may need multiple origin to be allowed. One use case is allowing developers only. To have this dynamic whitelisting, we may use this kind of function

const whitelist = ['http://developer1.com', 'http://developer2.com']
const corsOptions = {
origin: (origin, callback) => {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error())
    }
  }
}

2👍

set ‘supports_credentials’ => true, at config/cors.php
it works like a charm

1👍

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.

1👍

CORS ERROR With NETLIFY and HEROKU

Actually, if none of the above solutions worked for you then you might wanna try this.
In my case, the backend was running on Heroku and the frontend was hosted on netlify.
in the .env file, of the frontend, the server_url was written as

REACT_APP_server_url = "https://ci-cd-backend.herokuapp.com"

and in the backend, all my api calls where written as,

app.get('/login', (req, res, err) => {});

So, Only change you need to do is, add /api at the end of the routes,

so, frontend base url will look like,

REACT_APP_server_url = "https://ci-cd-backend.herokuapp.com/api"

and backend apis should be written as,

app.get('/api/login', (req, res, err) => {})

This worked in my case, and I believe this problem is specifically related when the front end is hosted on netlify.

Leave a comment