0

My angular app connects to an AdonisJS rest api thatrequires an auth token to work. This token is generated on succesful login however storing it for future requests is a problem. Ive tried to use window.sessionStorage but unfortunately this remains undefined until the user refreshes the page. Which means my angular app doesent get the token and makes the app not to work until the page is refreshed. Any suggestions or alternatives??

Noble Eugene
  • 523
  • 1
  • 5
  • 15
  • You can store your token using localStorage or sessionStorage depending on your requirements just look at ngx-store library to make life easier. – lakshmi narayana Sep 17 '21 at 05:59

2 Answers2

1

An example:

First, in your auth.service.ts, 2 methods to store/get the token

// STORE the token in localstore:
setToken(token:string){

   // First, serialize it (but just if token is not string type).
   const tokenString:string = JSON.stringify( token );

   localStorage.setItem('token', tokenString);
}
 
// READ the token from localstorage and Deserialize
getToken(): string | null{
 
   let token = localStorage.getItem( 'token' );
 
   if( token !=null){

       // You just need to parse if you serialized it inside setToken() method
       token = JSON.parse(carItemsString);
  }
 
  return token;
 
}

Then, in your interceptor:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
} from '@angular/common/http';

import { AuthService } from '../_services/auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private authService: AuthService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
  
  const url="\yourAPI\endpoint";
  
    //  Get your token
    cont myToken = this.authService.getToken();
  
    
    // Add authorization header with token if available   
 

    if (myToken) {
    
       request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${currentUser.user.api_token}`,
            'Content-Type': 'application/json',
          },
          url,
        });
        
    } 
    
    ...
    }

enter image description here

More info about how to Adding and updating headers HERE More info about how to Use the interceptor for Intercepting requests and responsesHERE

-1

You can store your token using localStorage or sessionStorage depending on your requirements (Session storage vs localStorage on paragraph 1

If you are using Angular to make the subsequent requests, consider creating an HttpInterceptor that is responsible from reading the token from localStorage and puting it in the HTTP Header of the requests.

Bruno Farias
  • 785
  • 8
  • 22