Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store data like jwt token in Angular 8? Is there another way to store safely using localstorage or session storage?

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.

like image 883
Nikita P Avatar asked Sep 18 '25 13:09

Nikita P


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');
  }
}
like image 199
Shahid Manzoor Bhat Avatar answered Sep 21 '25 04:09

Shahid Manzoor Bhat