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;
        }
    }
}

2 Answers

1
Teach What I Learn On

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,
   }
})
0
Nartub On

When you get the auth token you can configure the axios instance with:

axios.defaults.headers.common['Authorization'] = `Bearer ${token}`

common means applying the header to every subsequent request, while you can also use other HTTP verb names if you want to apply a header to only one request type:

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

You will find more info in https://github.com/axios/axios#config-defaults