Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 3 + HttpClientModule and token from storage

I have build an interceptor for making HTTP requests to a PHP backend. This backend gives an JWT token to the app and I save this in the Ionic Storage. But I want to get that token from Storage and add it as an header to the HTTP request.

Below is my interceptor with and hardcoded token. This works and I get a response from the backend.

See update @ bottom of this post

http-interceptor.ts

import { HttpInterceptor, HttpRequest } from '@angular/common/http/';
import {HttpEvent, HttpHandler} from '@angular/common/http';
import { AuthProvider } from "../providers/auth/auth";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {Storage} from "@ionic/storage";

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const changedReq = req.clone({headers: req.headers.set('Authorization', 'Bearer MY TOKEN')});
        return next.handle(changedReq);
    }

}

But how do I get the token from storage into the header. I searched alot and most of the tutorials / examples are from the older HTTP module. If someone has an idea or has a up2date example ?

UPDATE

Oke below code send the token

intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
        return fromPromise(this.Auth.getToken())
            .switchMap(token => {
                const changedReq = req.clone({headers: req.headers.set('Authorization', 'Bearer ' + token )});

                return next.handle(changedReq);
            });
    }

With 1 exception, namely the first time I access that page :)

like image 506
PostMans Avatar asked Jan 04 '18 14:01

PostMans


2 Answers

You can save JWT token in, for example, localStorage

 localStorage.setItem('myToken', res.token);

and then access it with

localStorage.getItem('myToken');

In your case something like this:

import { HttpInterceptor, HttpRequest } from '@angular/common/http/';
import {HttpEvent, HttpHandler} from '@angular/common/http';
import { AuthProvider } from "../providers/auth/auth";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {Storage} from "@ionic/storage";

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const changedReq = req.clone({headers: req.headers.set('Authorization', localStorage.getItem('myToken'))});
        return next.handle(changedReq);
    }

}

If you want to use Ionic Storage

import { HttpInterceptor, HttpRequest } from '@angular/common/http/';
    import {HttpEvent, HttpHandler} from '@angular/common/http';
    import { AuthProvider } from "../providers/auth/auth";
    import {Injectable} from "@angular/core";
    import {Observable} from "rxjs/Observable";
    import {Storage} from "@ionic/storage";

   @Injectable()
    export class TokenInterceptor implements HttpInterceptor {

    constructor(public _storage: Storage) {
         _storage.get('myToken').then((val) => {
         console.log('Your age is', val);
         });
    }

       intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            const changedReq = req.clone({headers: req.headers.set('Authorization', this.val)});
            return next.handle(changedReq);
        }

    }
like image 129
Tomislav Stankovic Avatar answered Sep 30 '22 06:09

Tomislav Stankovic


Caching the token in the interceptor is a bad idea because if the token changes the interceptor will not be aware of those changes.

// Don't do this.
token: string;
constructor(private storage: Storage) {
  this.storage.get('token').then((res) => {
     this.token = res;
  })
}

If you want to use Ionic Storage and the interceptor together you can do so by using Observable.flatMap like so...

app.module.ts

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true},
    SecurityStorageService
]

AuthInterceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(
  private securityStorageService: SecurityStorageService
) {}

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // This method gets a little tricky because the security token is behind a   
    // promise (which we convert to an observable). So we need to concat the 
    // observables.
    //  1. Get the token then use .map to return a request with the token populated in the header.
    //  2. Use .flatMap to concat the tokenObservable and next (httpHandler)
    //  3. .do will execute when the request returns
    const tokenObservable = this.securityStorageService.getSecurityTokenAsObservable().map(token => {
      return request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    });

    return tokenObservable.flatMap((req) => {
      return next.handle(req).do((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          // do stuff to the response here
        }
      }, (err: any) => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 401) {
            // not authorized error .. do something
          }
        }
      });
    })
  }

security-storage-service.ts

You technically don't need this service, but you shouldn't have Ionic Storage logic in your interceptor.

@Injectable()
export class SecurityStorageService {

  constructor(private storage: Storage) {

  }

  getSecurityToken() {
    return this.storage.get(StorageKeys.SecurityToken)
      .then(
      data => { return data },
      error => console.error(error)
    );
  }
  getSecurityTokenAsObservable() {
    return Observable.fromPromise(this.getSecurityToken());
  }
}

storage-keys.ts

export class StorageKeys {  
  public static readonly SecurityToken: string = "SecurityToken";
}
like image 44
Ryan E. Avatar answered Sep 30 '22 06:09

Ryan E.