Closed stojankukrika closed 6 years ago
I find a solution, maybe someone will have same problem so I post it here how I solve it:
post(endpoint: string, body: any, reqOpts?: any) {
let token = localStorage.getItem('infloo_token');
return this.http.post(this.url + '/' + endpoint, body, {
headers: {'Authorization': 'Bearer ' + token}
});
}
also can be done in other methods like get, put, delete or/and get.
All the best in new Year to all good people in word!
@stojankukrika you may store token in cookie, so every request will send cookie with token to server automatically. In fact, the app is a browser shell with html, js resource locally.
Cookies have serious disadvantages and I would not suggest using them: https://auth0.com/docs/security/store-tokens#cookie-disadvantages
You can easily store the token in local storage or session storage as appropriate and then either sub-class the HTTP client to add the token to the header or create an interceptor to do it (depending on the HTTP service you are using) which will then make it such that it is sent with every POST.
Wrapping the POST like @stojankukrika did works well too and makes it such that the token is easily sent with all POSTs without having to resort to cookies (yuk)
@kensodemann thanks, but as the article said, We strongly recommend that you store your tokens in local storage/session storage or a cookie
, In fact, Web Storage has several disadvantages too. so is your advice based on Cookies can be vulnerable cross-site request forgery (CSRF or XSRF) attacks
?
@JerryMissTom - partially on that and partially on last bullet point (Can be difficult to implement if the application requires cross-domain access
). The disadvantages with Local Storage are much easier to deal with. In another article they go into more depth and also state Again, as our recommendation is to store the JWT in local storage, you probably will not have to worry about XSRF attacks.
I tend to agree with Auth0 on the general advice to favor local storage, but feel free to use whatever works for you. I have always found using local storage and either an interceptor or subclass of the HTTP service to be the cleanest and most straight forward implementation to follow.
@kensodemann thanks for your reply, I learn more.
I have question about this generic REST Api handler. How to I add JWT token in headers and send it with other data? I save token in local storage.