Request header field Authorization is not allowed by Access-Control-Allow-Headers Error - express

I have a VueJS application and a ExpressJS server side application. On my server I have the following:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
}
app.use(allowCrossDomain);
However, I keep getting the following error:
Request header field Authorization is not allowed by
Access-Control-Allow-Headers in preflight response.
I'm sending my request like this:
import axios from 'axios'
export default axios.create({
baseURL: 'https://example.com',
timeout: 5000,
headers: {
'Authorization': 'Bearer ' + accessToken
}
})
How can I get around this? I have tried many solutions and read up on this. I have read the below:
How to allow CORS?
CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

The code in the question apparently isn’t causing the Access-Control-Allow-Headers header to get sent for OPTIONS responses — specifically, for the response to the CORS preflight OPTIONS.
To ensure preflight OPTIONS get handled correctly, consider installing the npm cors package:
npm install cors
And then do something like this:
var express = require('express')
, cors = require('cors')
, app = express();
app.options('*', cors()); // preflight OPTIONS; put before other routes
That will handle CORS preflight OPTIONS requests and other CORS aspects without you needing to manually write your own handling from scratch in your application code.
https://www.npmjs.com/package/cors#configuration-option has more details on all the options.

Related

CORS preflights error when using redirect

I`m trying to realize redirecting to another page of my app (current location 'http://localhost:3000/create-item' redirect to 'http://localhost:3000/subscribe') after saving item to database on my express server using next code (client send POST message to endpoint with form data):
await item.save();
res.writeHead(302, { Location: 'http://localhost:3000/subscribe' });
res.end();
one more variant:
await item.save();
res.redirect('/subscribe');
In base file of my server index.js i use my custom CORS middleware:
//cors.middleware.js
function cors(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, PATCH, POST, DELETE, OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization',
);
next();
}
module.exports = cors;
//index.js
const corsMiddleware = require('./middleware/cors.middleware');
app.use(corsMiddleware);
I also tryed:
npm i cors
app.use(cors());
Nevertheless I recieve CORS error while redirecting. So, what I`m doing wrong? Maybe this is related to sending data with POST method (redirect inside GET endpoint working well without CORS erro)

CORS don't work after JWT authentication added

I have a Vue frontend, an Auth0 and Fastify backend. CORS is configured as follows:
fastify.register(require('fastify-cors'), {
origin: 'http://localhost:8080',
methods: 'GET,PUT,POST,DELETE,OPTIONS,HEAD',
allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
})
Frontend headers configuration:
this.$auth.getTokenSilently().then(token => {
this.headers = {
Authorization: `Bearer ${token}` // send the access token through the 'Authorization' header
};
The problem is common:
Access to XMLHttpRequest at 'http://127.0.0.1:3000/dir' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've read a lot about CORS, know this is a browser side problem (Insomnia sends requests perfectly). Actually, I do not have clear understanding of what else I should allow and how. Basically I need only standart GET, PUT, POST, DELETE requests allowed. Could you please point out the exact configuration problems in my code?
First 401 was caused by OPTIONS request without autentication token. Actually it should be seamlessly processed by a fastify-cors. But due to an incorrect order of initialisation of on-request hooks (first - mine to autenticate, using fastify-auth0-verify, second - implicit hook from fastify-cors), it never invoked. So you need a precise order of hooks explicit and implicit initialization: first - cors, then second - authentication.
The second problem, 401 on the following POST, happened because of incorrect usage of an axios request params on the frontend Vue side. Headers like { Authorization: 'Bearer SomeVeryLongSecretXYZ'}were passed as, for instance, ...post(url, data, this.headers), but there must be {headers : this.headers}.
Final configuration for CORS:
fastify.register(require('fastify-cors'), {
origin: '*',
methods: 'GET,PUT,POST,DELETE,OPTIONS',
})

Request Failed when Add custom headers Vue

I'm doing a request with Axios but this fail when add custom headers (custom headers are required by the API).
If add the custom headers the response is:
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I have seen that two requests are made:
1- firs request:
2- Second request
In the API are enabled CORS
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-
Type, Accept, Access-Control-Request-Method,t-id-establecimiento,bt-
username,bt-nombre-empleado,ipaddress");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
My request in Vue:
let headers = this.getHeader()
this.$http(`${mUrl}`,{headers})
.then(function (resp) {
console.log(resp.data)
})
.catch(function (err) {
console.log('rerrrr' + err)
})
My custom header:
{
'Authorization': "Bearer " + urlParams.get('token'),
'Content-Type': 'application/json',
'bt-id-establecimiento': urlParams.get('bt-id-establecimiento'),
'bt-username': urlParams.get('bt-username'),
'bt-nombre-empleado': urlParams.get('bt-nombre-empleado'),
'ipaddress': urlParams.get('ipaddress'),
}
When dealing with a CORS error, most of the time you do not need to modify your request headers. 99% of the time, the problem is in the backend. Make sure to allow CORS in:
Server Configuration and
Application
If you are using XAMPP or any Apache server, by default CORS is not enabled. Although you already allow CORS on your application, it will still be blocked by the server.
Take note: make sure to restart your server when making changes to the configuration file

Vue.js - CORS error in local and production

I have got a file that's name is request.js,
import axios from 'axios'
const baseURL = 'https://SOME_URL.com/api/'
const config = {
baseURL,
timeout: 10000,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
}
}
const request = axios.create(config)
export default request
and I'm trying to send request in Vuex Actions;
import request from '../request'
const actions = {
postData(_, payload){
return request.post('a-request-url', payload)
}
}
Sending 2 requests and throws a CORS error when I run request. CORS error Access to XMLHttpRequest at 'https://crm.clinic/api/crm/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
AND 2 requests like;
and the real problem, cors error continious when deploy my code as production. Can you help me?
If you read the second part in the error it says where the issue is.
Request header field access-control-allow-origin is not allowed by
Access-Control-Allow-Headers in preflight response
As you can see you need to allow access in preflight response. A preflight request is something the browser does before sending your actual GET/POST/etc request. In the devtools' network tab you have 2 requests for the /login url. First one is a preflight using OPTIONS method.
To fix the issue you need to make sure your backend server returns 'Access-Control-Allow-Origin': 'http://localhost:8080' header in it's response for OPTIONS requests. Currently it is specifying only allowed methods and headers. You don't need to add those headers to your axios request.

Authorization header not passed on even tho it's allowed

I'm unable to retrieve Authorization header from requests where I send with CORS even though I've allowed 'Authorization' in 'Access-Control-Allow-Headers'. Sending with postman works.
Tried multiple different request methods including: request, axios and qwest. None of them work.
//Access Control in index.js before route.
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers, Cache-Control");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT")
next();
});
Expected result: Getting data back.
Actual output:
403 error forbidden because server can't get authorization header and error: 'Access to XMLHttpRequest at 'http://localhost:5000/api/cases/list?page=1&size=10' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.'
Switching to the cors module for express solved my issue. I replaced that whole block with
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"allowedHeaders": ['Authorization', 'Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Access-Control-Request-Method', 'Access-Control-Request-Headers', 'Cache-Control']
}))
which works. Really weird issue but I'm not gonna keep trying to figure out why it doesn't work.