The Same Origin Policy disallows reading the remote resource at (Reason: CORS header ‘Access-Control-Allow-Origin’ missing) - vue.js

I have a CORS problem that I believe had all settings configured correctly. The request passed OPTIONS preflight without a problem but the POST request has a CORS issue of CORS header ‘Access-Control-Allow-Origin’ missing. I have no idea why this would happen as other GET request and OPTIONS request are working fine. The api requires a Cookie and X-X-XSRF-TOKEN. And I can access these api data in POSTMAN.
Is it because of the request payload?
My Chrome Error:
Access to XMLHttpRequest at 'http://example.com:8080/login' from origin 'http://example.com' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I have added:
axios.defaults.withCredentials = true
axios.defaults.crossDomain = true
My post request:
async submitLogin() {
const headers = { "Content-Type": "multipart/form-data" };
const formData = new FormData();
formData.append("username", "example1");
formData.append("password", "example1");
axios
.post("http://example.com:8080/login", formData, {
headers: headers,
})
.then(function (response) {
console.log(response);
});
},
My Tomcat web.xml Config:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://example.com</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,DELETE,PUT,OPTIONS</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Cache-Control,Accept-Language,Accept-Encoding,x-requested-with, Content-Type, origin, authorization, Accept,Content-Length, Connection,Referer,client-security-token,Access-Control-Allow-Credentials,Cookie,Authorization,Content-Type,X-Requested-With,accept,X-XSRF-TOKEN,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Successfully passed OPTIONS Preflight Request
Request Header

Try modifying your web.xml config's cors.allowed.origins param to *.
You're generally pretty safe with GET requests unless the receiving server's settings are strict — GETs aren't discriminated against in the CORS universe in the same way POST requests are. That may be why you're noticing the discrepancy you mentioned. Postman also doesn't face the same restrictions that a browser does.
If changing cors.allowed.origins doesn't work, try inspecting the error message in the devtools console in more than one browser; sometimes one browser is more specific than the next and will point you in the right direction.

Related

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.

Apache httpd returns multiple values for CORS

I am writing a web app that request data from another service I have deployed.
I have configured Apache httpd as a proxy to my web app.
...
Header always set Access-Control-Allow-Origin: http://localhost:8080
Header always set Access-Control-Allow-Methods: "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Credentials: true
...
Sending a request using jquery:
$ajax('https://service.com/path',{
method: "POST",
xhrFields: {
withCredentials: true
}
})
I am sending a request with a token saved in the cookie.
The response I am getting is:
XMLHttpRequest cannot load https://service.com/path`. The 'Access-Control-Allow-Origin' header contains multiple values 'https://myapp.com, *', but only one is allowed.
What have I configured wrong?

Request doesn't pass access control check: No 'Access-Control-Allow-Origin'

I am just trying to use mocky.io from my http://localhost:8080
But getting this error:
XMLHttpRequest cannot load http://www.mocky.io/v2/5715f13a1100004d1187d9e1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
My request looking like that:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
this.people = http.get('http://www.mocky.io/v2/5715f13a1100004d1187d9e1', { headers: headers })
.map(response => response.json());
Actually you should setup the header Access-Control-Allow-Origin in mocky.io.
Just click on "Switch to Advanced mode" and you will see a "custom headers" input. Add Access-Control-Allow-Origin and put * as its value. Then create your mocky.io url. It should work now.
It is looks like you are trying to access to other domain.
Maybe add this in the web.config?
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="http://localhost" /> </customHeaders> </httpProtocol>