Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set authorization header in vue.js

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;
        }
    }
}
like image 240
Krishna Avatar asked Sep 14 '25 11:09

Krishna


1 Answers

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,
   }
})
like image 136
gokublack Avatar answered Sep 17 '25 04:09

gokublack