Request header field authorization - vue.js

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:
]

Related

Axios request to AEM servlet redirecting to login.html

I have a working servlet that tests properly with Postman, but I can't get the request to execute from the front end. The fact that Postman can execute the servlet with either a Get or a Post tells me the problem is likely with the front-end code.
Does anyone see where the misconfiguration is in this block? The Basic key and cookie are copied from Postman, there is no CORs problem.
const response = await axios.get(url, null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Accept': '*/*',
'Content-type': 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
'Authorization': 'Basic YWRtaW46YWRtaW4='
},
withCredentials: true,
Cookie: "cq-authoring-mode=TOUCH;",
params: {
path: rootPath,
maxCount: sourceMax
}
}).catch(err => {
console.log(err)
}, () => {
console.log(response)
}).then(res => {
console.log(res)
})
This is most likely the CSRF filter which rejects some requests that don’t contain a CSRF token. By default it checks only POST, PUT and DELETE requests.
It’s weird that it also checks your request, which seems to be a GET. Either your filter is configured differently or you sending a Content-type header – which describes the request body content type – makes axios switch the request from GET to POST (because GETs don’t have a request body and, thus, don’t need to declare their content type).
The CSRF filter can be configured in various ways and can exclude certain requests from filtering by path or user-agent:
You could also request a token from the /libs/granite/csrf/token.json endpoint and then send it along in your request. One way to do this is via the query, as the :cq_csrf_token param.

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.

Sending axios get request with authorization header

I have tried to send axios get request using vue.js and it worked just fine when there was no need to send headers. However, when it was required to send an authorization jwt, i was getting CORS error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." I don't know why is this problem occurring since there is Access-Control-Allow-Origin: '*' header in the response. My code is the following:
axios.get(url, {
headers: {
'Authorization': 'Bearer TOKEN'
}
})
.then(function (response) {
console.log(response.data)
})
The weirdest thing is when I use querystring.stringify or JSON.stringify on the header, I don't get the error 403(forbidden), but just an error 401 - Unauthorized. I tried with variable and with the token itself and it didn't work.
I tried to send a post request in order to get a web token with required data - username an password and it worked. I was able to get the token.
I made a whole bunch of research the last two days on this and I found different kind of request structure and configs which I tried all of them, but none were efficient. Is there a way to check if the request is being send with the header? Is something else the problem? If someone can help, I would appreciate. Thanks.
I think you should add this code to the bootstrap.js (or where the axios is defined):
window.axios = require('axios'); // I think its already added
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest'
};
You didn't mention, but I guess you use laravel, or other framework, what is protected from csrf attack, thats why you need to add the generated token to your ajax request header.