Authorization header not passed on even tho it's allowed - express

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.

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)

Request header field authorization

I am trying to create "UUID" form this Api call
I am using axios and vue.js. Here's my source code.
generateUUID() {
// console.log("call generate uuid");
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*'
}
axios.get('https://www.uuidtools.com/api/generate/v1', {
headers: headers
}).then(response => console.log(response))
},
But unfortunately I am getting
Access to XMLHttpRequest at 'https://www.uuidtools.com/api/generate/v1' 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 have tried searching google and followed many answers already to that question but got nothing.
Problem(s)
Access-Control-Allow-Headers and Access-Control-Allow-Origin are response headers, not request headers. Specifying them in a request is more than useless; it's actually counterproductive, here.
Why would you specify a content type for a GET request? GET requests are not supposed to have a body:
A payload within a GET request message has no defined semantics;
sending a payload body on a GET request might cause some existing
implementations to reject the request.
According to my tests, the resource that you're requesting (https://www.uuidtools.com/api/generate/v1) appears to be CORS-aware but expects only simple requests, not preflight requests. And because your request contains headers that are not CORS-safelisted, it gets preflighted by your browser, and the preflight access-control check fails.
Solution
Just send a simple GET request (without adding any headers):
fetch('https://www.uuidtools.com/api/generate/v1')
.then(r => r.json())
.then(arr => arr[0])
.then(console.log)
Console output
No CORS error, then:
]

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

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

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.