简体   繁体   English

使用保存在vue.js中的cookies中的JWT从我的spring中获取用户object API用于持久登录

[英]Using JWT saved in cookies in vue.js to get a user object from my spring API for persisted log-in

I'm trying to mock up some persisted log-in for my first web application so the site is still functional after a refresh.我正在尝试为我的第一个 web 应用程序模拟一些持久登录,以便该站点在刷新后仍然可用。 When I print the token (which is saved in cookies) in the console, it prints normally.当我在控制台中打印令牌(保存在 cookie 中)时,它可以正常打印。 And when I use postman with the token in the header, I get the correct JSON response.当我将 postman 与 header 中的令牌一起使用时,我得到了正确的 JSON 响应。 However, when using it in the mounted method, I get a 401. So I believe it is an issue with the way I'm am implementing my headers in my fetch.但是,在安装方法中使用它时,我得到 401。所以我认为这是我在提取中实现标头的方式的问题。 Thanks in advance, as I am extremely new to coding.在此先感谢,因为我对编码非常陌生。

 mounted: function() { console.log(this.$cookies.get('token')); let t = JSON.parse(JSON.stringify(this.$cookies.get('token'))); let h = new Headers(); h.append('Authentication', `Bearer ${t}`); fetch('http://localhost:8080/api/owner/persist', { method: 'GET', headers: h }).then((response) => { return response.json(); }).then((data) => { this.jwtUser = data; })

Java Controller below: if I have the PreAuthorize Tag, I get a 401 error, and if I take it away I get a null pointer exception. Java Controller 下面:如果我有 PreAuthorize 标签,我会得到一个 401 错误,如果我把它拿走,我会得到一个 null 指针异常。 I think its just something wrong with the formatting of my header. Which I have been messing around with a lot.我认为我的 header 的格式有问题。我一直在搞乱它。

 @PreAuthorize("isAuthenticated()") @RequestMapping(path = "api/owner/persist", method = RequestMethod.GET) public Owner persistedLogin(Principal principal) { Owner o = new Owner(); o = ownerDAO.getOwnerInfoByName(principal.getName()); return o; }

The standard way to transport access tokens, and especially JWTs, is the header called Authorization .传输访问令牌(尤其是 JWT)的标准方式是 header,称为Authorization

In your code example you are using Authentication which is from a description point of view correct as JWTs are in the first step authenticating a request and only at the second step source for authorization.在您的代码示例中,您使用的Authentication从描述的角度来看是正确的,因为 JWT 在第一步中对请求进行身份验证,并且仅在第二步源中进行授权。 But the standard header is like it is and was named Authorization .但是标准 header 就像它一样,被命名为Authorization Your formatting of the header-value ( Bearer <token> ) looks correct to me.您对标头值 ( Bearer <token> ) 的格式在我看来是正确的。

Double check the correct name of your header that needs to carry the token, and verify you are using the correct one which is working as you stated in your test with Postman.仔细检查需要携带令牌的 header 的正确名称,并确认您使用的是正确的名称,它按照您在 Postman 的测试中所述工作。

Best, cobz最好的,cobz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM