简体   繁体   中英

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. When I print the token (which is saved in cookies) in the console, it prints normally. And when I use postman with the token in the header, I get the correct JSON response. 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. 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. I think its just something wrong with the formatting of my header. Which I have been messing around with a lot.

 @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 .

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. But the standard header is like it is and was named Authorization . Your formatting of the header-value ( Bearer <token> ) looks correct to me.

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.

Best, cobz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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