Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store token in Local or Session Storage in Angular 2?

I want to use Local or session storage to save authentication token in angular 2.0.0. I use angular2-localstorage but it works only angular 2.0.0-rc.5 and when I used it in 2.0.0 it through me Type error. I want to use default local storage of Angular 2.0.0.

like image 341
Rahul dev Avatar asked Oct 03 '16 21:10

Rahul dev


People also ask

Should I store token in local storage?

To reiterate, whatever you do, don't store a JWT in local storage (or session storage). If any of the third-party scripts you include in your page is compromised, it can access all your users' tokens. To keep them secure, you should always store JWTs inside an httpOnly cookie.

Should we store token in localStorage or cookie?

Conclusion. Both cookies and localStorage are vulnerable to XSS attacks. However, cookie-based token storage is more likely to mitigate these types of attacks if implemented securely. The OWASP community recommends storing tokens using cookies because of its many secure configuration options.

Can localStorage store access token?

Storing tokens in browser local storage provides persistence across page refreshes and browser tabs, however if an attacker can achieve running JavaScript in the SPA using a cross-site scripting (XSS) attack, they can retrieve the tokens stored in local storage.


1 Answers

Save to local storage

localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name })); 

Load from local storage

var currentUser = JSON.parse(localStorage.getItem('currentUser')); var token = currentUser.token; // your token 

For more I suggest you go through this tutorial: Angular 2 JWT Authentication Example & Tutorial

like image 59
Bojan Kogoj Avatar answered Sep 20 '22 18:09

Bojan Kogoj