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.
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With