How to add Authorization header in vueJs - spring-boot

I'm trying to send a post request from a vuejs app to a spring backend with which I'm attaching a jwt authorization header.
I have tried with vue-resource
Vue.http.headers.common['Authorization'] = 'Bearer YXBpOnBhc3N3b3Jk';
and the backend headers are like this
{accept-language=en-US,en;q=0.5, origin=http://localhost:8080, host=127.0.0.1:8084, access-control-request-headers=authorization, connection=keep-alive,...
But if i use postman to send the same request, the backend headers are like this
{authorization=Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1OTBhYWFmMjRhNjQ3ZjRiYmZlMDBhMDQiLCJzdWIiOiJiYmIiLCJpYXQiOjE0OTM5NzUxMDQsInJvbGVzIjoidXNlciIsImV4cCI6MTQ5Mzk3NTQ2NH0.kldUh3H1i3xEiNcxQ2ecq1HsjIIF5BI8Q-tb3sALc3E, content-length=0, accept-language=en-US,en;q=0.8,.......
My question is, how can i achieve the postman header using vuejs. I have tried with axios as well but without success.

Try this way with axios. I'm using spring backend too and it works..
axios.post(
url,
query ,
{headers: {
"header name" : "header value"
}}
)
.then((response) => {
var response = response.data;
}, (error) => {
var error = error.response;
}
}
)

Related

Axios not sending XSRF token with headers

I am integrating a Vue JS (Quasar framework) based SPA with API. The API is built in Laravel and is using sanctum for CSRF.
When I send a request to the sanctum endpoint https://someweburl.com/sanctum/csrf-cookie it sends the XSRF-TOKEN as cookie correctly. But when I am sending the the POST request, the X-XSRF-TOKEN is not attaching itself with the header. And I am getting a 'token mismatch' error.
The front-end is on my localhost:8080 while the API is live on a url. I do not have direct access to the Laravel project but only the API.
Following is my axios configuration
import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$axios = axios;
const apiBaseUrl = "https://someweburl.com";
const api = axios.create({ baseURL: apiBaseUrl });
api.defaults.withCredentials = true;
Vue.prototype.$api = api;
Vue.prototype.$apiBaseURL = apiBaseUrl;
export { axios, api, apiBaseUrl }
Following is the request format that I am trying to achieve i.e A POST request after getting the CSRF
export const fetchAllEvents = async function (context, payload) {
this._vm.$api.get('/sanctum/csrf-cookie').then(response => {
this._vm.$api.post('/api/website/event/all').then(response => {
context.commit('setAllEvents', response.data.data);
}).catch(error => {
console.log(error);
})
}).catch(error => {
console.log(error);
})
}
When I check use Postman to make the POST request with X-XSRF-TOKEN added as header, i am getting the correct response. Which means the API is working correctly. But there's some issue with axios.
Any help will be appreciated.
Maybe that is because the Axios only sets the X-XSRF-TOKEN header when the front and backend have the exact origin. You mentioned you are trying with your frontend app at your localhost and the API is on the web at another URL.
See the axios GitHub repository for more information: https://github.com/axios/axios/blob/cd8989a987f994c79148bb0cacfca3379ca27414/lib/adapters/xhr.js#L179

sending refresh token in headers to Laravel backend

Using Postman I'm able to POST my refreshToken:
.
In my controller I can receive above token like so:
$request->header('refreshToken');
If I try to do the same using axios I receive the data in $request->refreshToken not in header
axios.post(
'mybackend/refreshToken',
{ 'refreshToken': myToken }
)
tried the 'headers' option in axios but no luck.
$request->header('refreshToken'); // I should receive the token here, from axios
I think you are sending the refreshToken in the body instead of the header.
It should be:
axios.post(
'mybackend/refreshToken',
{}, //body
{headers:{ 'refreshToken': myToken }} //header
)

Axios JWT doesn't send

I have a project divided in two layers. The back-end is developed in spring boot, secured by Sprint security and JWT, and the front-end is developed in Vue.js, using Axios library for communication between layers.
I receive the "Bearer token" authentication properly, and all the authentication process is done correctly. The issue appears when I try to send a request with a token header to access content but the token doesn't send, and the Spring boot returns null without the content.
Here is the code
getOffers: function () {
if (localStorage.getItem("userSession")) {
this.aux = JSON.parse(localStorage.getItem("userSession"));
this.token = this.aux.token;
this.tokenHeader = "Bearer "+this.token;
alert(this.tokenHeader)
};
console.log(`Bearer ${this.token}`)
axios.
get('http://localhost:8080/api/v1/offer', {'Authorization' : `Bearer ${this.token}`})
.then(response => {
console.log(response);
this.offers = response.data
}).catch(e => console.log(e))
}
P.S: When I make a request in Postman, it works fine and returns the desired object. Here is a postman example:
postman
Correct way to pass header is :
axios.get(uri, { headers: { "header1": "value1", "header2": "value2" } })
In your case try this:
axios.get('http://localhost:8080/api/v1/offer', { headers:{Authorization : `Bearer ${this.token}`} })
Also, check in console if this gives correct Bearer token:
console.log(`Bearer ${this.token}`)
Register the Bearer Token as a common header with Axios so that all outgoing HTTP requests automatically have it attached.
window.axios = require('axios')
let bearer = window.localStorage['auth_token']
if (bearer) {`enter code here`
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + bearer
}
And no need to send bearer token on every request.

Adding multiple headers to graphql client (apollo-boost)

const client = new ApolloClient({
uri,
onError: (e: any) => {
console.log('error: ', e); // Failed to fetch
console.log(e.operation.getContext()); // it does show it has x-abc-id
},
request: operation => {
const headers: { [x: string]: string } = {};
const accessToken = AuthService.getUser()?.accessToken;
const activeClientId = UserService.getActiveClientId();
headers['x-abc-id'] = activeClientId;
if (accessToken) headers['Authorization'] = `Bearer ${accessToken}`;
operation.setContext({ headers });
}
});
The problem here is when i just add Authorization header it makes the POST call and shows the expected error.
But when i add x-abc-id header which is also expected by backend it only makes OPTIONS call (no post call)
P.S. On postman adding both headers works completely fine.
Found what the issue was, thought to share if it help.
Postman does not perform OPTIONS call before sending request to backend.
In OPTIONS call, 👇represents what client call contains: [authorization, content-type, x-abc-id]
BUT what does server expects: 👇
Just authorization, content-type
So it's a calls headers mismatch (nothing related to Apollo).
x-abc-id header explicitly has to be allowed in CORS configuration on backend.
Thanks to Pooria Atarzadeh

Ionic 2 ASP APi token request

I'm Trying to retrieve a bearer token from my ASP API from my ionic2 app.
I have enabled CORS on the API as shown below:
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
This enabled me to form a POST request from my ionic 2 app to my API in order to register a user. This works wonderfully.
The request I used for this is as shown below:
let headers = new Headers({
'Content-Type': 'application/json'
});
let options = new RequestOptions({
headers: headers
});
let body = JSON.stringify({
Email: credentials.email,
Password: credentials.password,
ConfirmPassword: credentials.confirmPassword
});
return this.http.post('http://localhost:34417/api/Account/Register', body, options)
However when I try to retrieve a token from my API I receive the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
The request I'm using to try and retrieve the token is as follows:
let body = "grant_type=password" + "&userName=" + credentials.email + "&password=" + credentials.password;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:34417/token', body, options)
This is the only request that is throwing this error, all other requests to my API work fine.
Have I missed anything, or am I doing something wrong?
var cors = new EnableCorsAttribute("*", "*", "*");
Looks like you are setting Access-Control-Allow-Origin as *.
Check MDN CORS Requests with credentials.
Credentialed requests and wildcards
When responding to a credentialed request, the server must specify an
origin in the value of the Access-Control-Allow-Origin header, instead
of specifying the "*" wildcard.
You will have to set a specific url if you use credentials.
Or if you only intend to use only for ionic 2, you could avoid the cors issue by setting a proxy.
According to the official blog:
The proxies settings contain two things: the path you use to access them on your local Ionic server, and the proxyUrl you’d ultimately like to reach from the API call.
{
"name": "ionic-2-app",
"app_id": "my_id",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://localhost:34417/api"
}
]
}
Ionic serve command by default will start server on localhost:8100.
The set proxy will hit your http://localhost:34417/api.
Your path in the requests will be to the localhost:8100/api instead of your actual server.

Resources