I am using JWT tokens to authorise requests to my API from an angular 8 website. But where do i store this token which is not visible to user? i have tried using Service but after refresh page token gets lost.
-
1Any special reason for this? It's ok to keep tokens in localstorage – igor_c Dec 28 '19 at 09:49
-
@igor_c ok but wanted to store sensitive data securely. – Nikita P Dec 28 '19 at 11:23
1 Answers
You can make use of cookies to store the token instead of the local storage or session storage however thats not going to make it secure. Even encrytping the cookies or local storage isnt a fool-proof mechanism as the key for encryption would either reside on client side or passed from a server. Which makes it susceptible to modification.
For implementing a secure mechanism of handling your token I suggest you have a look at this answer
For having an alternative to local storage or session storage you can use cookies as follows:
You can install this package https://www.npmjs.com/package/ng2-cookies
Then you can simply follow the steps
import { Cookie } from 'ng2-cookies/ng2-cookies';
//setter for token
Cookie.set('jwtToken', 'tokenValue');
//getter for token
let token = Cookie.get('jwtToken');
//delete token cookie
Cookie.delete('jwtToken');
Or you can install NGX Cookie Service for version Angular 4 and above
Install
npm install ngx-cookie-service --save
Import and Inject into your component
import { CookieService } from 'ngx-cookie-service';
export class AppComponent implements OnInit {
constructor( private cookieService: CookieService, private _authService: AuthService ) { }
ngOnInit(): void {
//call your auth service to get the token, I have made a call to a dummy auth service to fetch the token
var token = _authService.GetToken();
//Set auth token cookie
this.cookieService.set( 'authToken', token );
//get auth token cookie
this.cookieValue = this.cookieService.get('authToken');
}
}

- 1,307
- 1
- 13
- 32
-
1This is still not secure. Anything that is on the clients device(browser) can be manipulated by the user. – nightElf91 Dec 28 '19 at 11:25
-
@nightElf91 absolutely, the OP was asking for an option to store the token without using local storage or session storage and I agree with your point encrypting things on client side has no sense, since the key would be stored in client code its susceptible to modification – Shahid Manzoor Bhat Dec 28 '19 at 11:39
-
1
-
Why isn't token encryption still insecure? I mean if you store the key in the code and protect your code - then what is the problem? – Andrеw Oct 26 '22 at 05:49