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,
   }
})
Share:
17,853
Krishna
Author by

Krishna

Updated on June 04, 2022

Comments

  • Krishna
    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
    Krishna almost 5 years
    I tried this before. It didn't work. I do not see any headers set in OPTIONS request
  • gokublack
    gokublack almost 5 years
    can 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
    Krishna almost 5 years
    I don't see any headers
  • Krishna
    Krishna almost 5 years
    when I set the headers, it is not showing up in the chrome developer tools -> network -> Request headers
  • Nartub
    Nartub almost 5 years
    Can you update your question with the portion of the code where you are receiving the token and configuring it in axios?
  • Nartub
    Nartub almost 5 years
    I think axios.defaults.headers.common["X-XSRF-TOKEN"] = token; should be axios.defaults.headers.common["Authorization"] = 'Bearer ' + token;
  • Viorel
    Viorel over 4 years
    Did you check if you added OPTIONS to your CORS configuration? configuration.addAllowedMethod(HttpMethod.OPTIONS);