How to set authorization header in vue.js
17,853
Setting Authorization Header is not something to do with vue, but it is something to do with axios.
axios.post("http://localhost:8004/api/v1/getdata", {"action" : "dashboard"}, {
headers: {
Authorization: 'Bearer ' + token,
}
})
Author by
Krishna
Updated on June 04, 2022Comments
-
Krishna almost 2 years
I'm making an axios post call with the JWT token generated after successful login. For all the requests I need to attach JWT token in header and in the back-end which is developed on spring -boot I have logic to get the token from header and validate it.
From the browser, first the OPTIONS request goes to back-end where it gives me 403 error and in the back-end If I sysout headers, I can't find the header name X-XSRF-TOKEN
axios.post("http://localhost:8004/api/v1/auth", { "username": "test", "password" : "test"}) .then((response) => { let token = response.data.token; axios.defaults.headers.common["X-XSRF-TOKEN"] = token; axios.post("http://localhost:8004/api/v1/getdata", {"action" : "dashboard"}) .then((response) => { console.log(response.data); }, (error) => { console.log(error); }) }, (error) => { console.log(error); })
Spring boot part
@Controller @CrossOrigin(origins = "*", allowedHeaders = "*") @RequestMapping(path = "/api/v1") public class ApplicationController { @PostMapping(path = "/getdata") @ResponseBody public SessionData getData(@RequestBody ProfileRequest profileRequest) { try { return profileService.getData(profileRequest); } catch (Exception e) { e.printStackTrace(); return null; } } }
-
Krishna almost 5 yearsI tried this before. It didn't work. I do not see any headers set in OPTIONS request
-
gokublack almost 5 yearscan you check the network request for the request header information, perhaps you could use chrome developer tools network panel and check whether you get the header properly in the request
-
Krishna almost 5 yearsI don't see any headers
-
Krishna almost 5 yearswhen I set the headers, it is not showing up in the chrome developer tools -> network -> Request headers
-
Nartub almost 5 yearsCan you update your question with the portion of the code where you are receiving the token and configuring it in axios?
-
Nartub almost 5 yearsI think
axios.defaults.headers.common["X-XSRF-TOKEN"] = token;
should beaxios.defaults.headers.common["Authorization"] = 'Bearer ' + token;
-
Viorel over 4 yearsDid you check if you added OPTIONS to your CORS configuration?
configuration.addAllowedMethod(HttpMethod.OPTIONS);