Can't set authorization and token in headers with axios in VueJS - vue.js

I'm trying to set a JWT token authentication on a VueJS client and PHP API (using Zend and firebase).
I manage to log an user in with the creation of a JWT token stored in LocalStorage. Now I would like to send back this token to the API (so as to the API decode the JWT and return associated infos). I try to set the "Authorisation: Bearer + token" in the header from VueJS using axios but I always have a problem.
Here is a code snippet :
function getInfos() {
return axios({
method: 'get',
url: MYURL,
headers: {
Authorization: 'Bearer ' + localStorage.getItem('user')
}
})
.catch(handleResponse)
}
First I got this error :
Access to XMLHttpRequest at 'MYURL' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Then I don't have any Authorization in header when I want it in my PHP API :
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: *');
$request = new Request();
I know that I probably have to use
axios.defaults.headers.post or maybe axios.interceptors but I'm a beginner so I have no idea how to use it properly..
I hope someone will be able to help me ! Thank you

I think * doesn't work when setting custom headers you have to Type in header('Access-Control-Allow-Headers: Authorization') atleast that's an issue i had

Related

Sync Token in Postman

A fresher to postman, currently working on API project where I need to delivery to the API and Token the client to integrate with them system, good is I successfully configure the Authorization as OAuth Type as Password Credentials and receiving perfect response as 200.
The issue/confusion is Token is getting expire every hour, I need to Get new Access Token every time.
So, the question is, is it anyway I can overcome this issue?
that no need to get new/refresh token.
can provide the one fix token to client.
You can do it like here. You can get the token in the pre-request field of the collection or request.
https://stackoverflow.com/a/73911458/10126763
EDIT
We can adapt it like this:
Take this and paste it in the "pre-request" field of the collection or the request you will use directly. Create an "environment" value named "accessToken". When each request is run, this method will run first and send the token value to the value in the environment.
// Set refresh and access tokens
const loginRequest = {
url: "exampleurl.com/etc/etc", //YOUR URL
method: 'GET',
header: {
'content-type': 'application/json',
'Accept': "*/*"
} //Since you will be using GET, I deleted the body. If you are sending value you can get the body field from the other example in the link.
};
pm.sendRequest(loginRequest, function (err, res) {
pm.environment.set("accessToken", res.json().accessToken); //The token returned in the response and the environment value to which the value will be sent
});

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',
})

How to store jwt token in localStorage and send it back to the server with header in express?

I have read many articles in stackoverflow and have seen lots of youtube videos, but failed to find the example code which is demonstrating about the flow of saving jwt to localstorage - send back to server with authorization header for verifying.
Here is what I want to do.
When the client logs in to the server, server gives token and saves it to the client localStorage (or sessionStorage).
Whenever the client calls an api which can be accessed only with the token,
client retrieves the token back from the localStorage, and send that token with the authorization header (req.headers.[x-access-token] or req.headers.[authorization]) to the server.
But all of the articles I've been read is explaining this issue with the Postman which does not show how to store it to the localStorage and put it in the authorization header.
Do I have to use localStorage.setItem when the server gives the token to the client, and use and localStorage.getItem and new Headers() with append() or axios before sending that token back to the server?
Examples don't have to be for the express user, but I'd like to get the glimpse of ideas.
You can store your jwt token in localstorage and when ever you make a API call you can add the token to headers as token. if you are using axios you can attach you token to headers like this. Here the token is stored in localstorage with the key 'jwtToken'
axios.post('http://yourendpoint',data,{ headers: { Authorization:localStorage.getItem('jwtToken') } })
.then(response=> console.log(response))
.catch(error => console.log(error));
};
it's easy just Follow me
First of all you have to save the Token(or access token) to the local storage,
in the login component when you are sending request for login do the below:
signin:function() {
axios.post('http://Somthing/log-in/',{
username: this.username,
password: this.password,
})
.then( (response) => {
let token = response.data.access;
localStorage.setItem("SavedToken", 'Bearer ' + token);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
(this.$router.push({name:'HomePage'}));
})
So now the problem is whenever you refresh the Homepage you got 401 error and the solution is : just add this :
{ headers: { Authorization:localStorage.getItem('SavedToken') }}
to the end of each request that need the Token in its header, like below:
axios.get('http://Something/', { headers: { Authorization:localStorage.getItem('SavedToken') }})
.then(response =>{
//something
})
Notice that the token that i used in this explanation was SIMPLEJWT , if you are using somthing else maybe you have to change 'Bearer' to somthing else.
First you have to create or Generate Token through Jwt (jsonWebTokens) then either store it in local Storage or through Cookie or through Session. I generally prefer local storage because it is easier to store token in local storage through SET and retrieve it using GET method. and after retrieving it through get you can verify it through jwt and also authenticate it with bearer authentication..
And for headers add Authorization
fetch("/users", {
method: "Get",
headers: {
"content-type": "application/json",
Authorization: "Bearer" + localStorage.getItem("token")
}
JWTs should never be stored in your localStorage
In fact, they shouldn't even be stored in your cookies, unless you are able to implement very strict CSRF protection
Checkout this for motivation
JWT as an id_token is like your user credentials
JWT as an access_token is like your session token
One option is in-memory. Checkout this for a deep dive

Couchdb Vue.js authentication

I'm trying to move a node/express authentication application over to vue.js. I am able to successfully authenticate getting a 200 code. However, the response returned from couchdb does not contain the "set-cookie" header, which contains the much needed AuthSession token. The code that I am using in my Vue component is:
var reqBody = "name="+user+"&password="+pass;
var reqBodyLength = reqBody.length;
console.log(reqBodyLength);
this.$http.post('http://localhost:5984/_session/', reqBody, {headers: {'Content-Type' : 'application/x-www-form-urlencoded', 'Accept' : 'application/json'}}).then(response => {
console.log("response: " + JSON.stringify(response));
console.log("response.headers: " + JSON.stringify(response.headers));
console.log("response.headers.set-cookie: " + JSON.stringify(response.headers["set-cookie"]));
}, response => {
alert('you unauthorized, fool!')
})
Has anyone ever had an issue getting the "set-cookie" header?
Thanks, Tyler
Couch's AuthSession is HttpOnly cookie and therefore can't be accessed through a client side script. But the cookie itself should be set to a browser by that _session query, so all the consequent requests will be authorized.
BTW, /_session also accepts JSON payload, at least in CouchDB 1.6, so the query doesn't have to be in x-www-form-urlencoded form.

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.