如何在vue.js中设置授权标头

时间:2019-05-10 10:58:17

标签: spring-boot vue.js spring-security axios

我正在使用成功登录后生成的JWT令牌进行axios后期呼叫。对于所有请求,我都需要在标头和在spring -boot开发的后端中附加JWT令牌,我有逻辑从标头获取令牌并对其进行验证。

在浏览器中,首先OPTIONS请求转到后端,该错误使我收到403错误;在后端,如果我sysout标头,则找不到标头名称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);
})

弹簧靴部件

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

3 个答案:

答案 0 :(得分:1)

  

设置授权标头与vue无关,但可以   与axios有关。

axios.post("http://localhost:8004/api/v1/getdata", {"action" : "dashboard"}, {
   headers: {
      Authorization: 'Bearer ' + token,
   }
})

答案 1 :(得分:0)

获得身份验证令牌后,可以使用以下命令配置axios实例:

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

common意味着将标头应用于每个后续请求,而如果只想将标头应用于一种请求类型,则还可以使用其他HTTP动词名称:

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

您将在https://github.com/axios/axios#config-defaults

中找到更多信息。

答案 2 :(得分:0)

...
axios.post('http://localhost:8004/api/v1/auth', 
{ "username": "test", "password" : "test"}, {headers: { X-XSRF-TOKEN: `${token}`}})
...

问题可能不是axios,而是spring security设置的cors策略。

如果您正在使用Spring Security,请查看此answer

我遇到了同样的问题,这个答案帮助解决了我的问题。