Ionic 3 + HttpClientModule and token from storage

ionic 4 interceptor
ionic set authorization header
ionic 4 http headers
ionic storage
ionic 3 local storage example
how to set header in ionic 3
ionic 3 http headers
ionic native http interceptor

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 :)

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);
        }

    }

Authorisation Headers with Ionic using HTTP Interceptor and , Inside those requests we will use a token that we store and retrieve from 3. ionic start interceptMe blank. cd ionic start interceptMe blank Also, we add the HttpClientModule and IonicStorageModule to prepare everything. In this Quick Win we will add a custom HTTP interceptor which will intercept all outgoing HTTP calls that our Ionic app makes. Inside those requests we will use a token that we store and retrieve from the Ionic Storage and also catch any errors that happens at the top most level inside the app.

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";
}

Interceptor Refresh JWT Token with ionic storage(Promise)?, Ionic 3 + HttpClientModule and token from storage. ionic-framework, angular-http​-interceptors. asked by PostMans on 02:59PM - 04 Jan 18  I am trying to implement JWT in my Ionic 3 app, and have been using angular2-jwt successfully before (without HttpInterceptor). But the master v1.0 branch doesn't seem to working, with all modules fully updated.

For anyone who comes across this like me and is using rxjs >=5.5.0 then you can just do:

auth-interceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(private authService: AuthService) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return from(this.authService.getToken()).pipe(mergeMap((token) => {
        const changedReq = req.clone({
            setHeaders: {
                Authorization: `Bearer ${token}`
            }
        });

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

auth-service.ts

public async getToken() {
    return await this.storage.get('ACCESS_TOKEN');
}

Authorization Header not added within Ionic 3 · Issue #460 · auth0 , 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. Setting up Ionic Storage Module. The Ionic team provides the Ionic Storage module that can be used to work with the browser's local storage in mobile devices but before we can use it in our application, we need to install it from npm and import it in our authentication module. Head back to your terminal and run the following command:

Change ionic token getter in ionic 3 · Issue #463 · auth0/angular2 , I am trying to implement JWT in my Ionic 3 app, and have been using import { HttpClientModule } from '@angular/common/http'; const storage = new tokenGetter(); console.log("This outputs a Promise having the token",  Install or update Ionic 3 using this command; Optionally install or update Cordova if you're using it for a run on the Android or iOS device; sudo npm install -g ionic sudo npm install -g cordova Create the New Ionic 3 App. As usual, we are creating new Ionic 3 app from scratch. Open the terminal or Node command line then type this command.

JWT Authentication with Ionic & Node.js, Hello I am building a pwa using ionic3. If the platform is browser I will set the token in session storage and if @NgModule({ declarations: [ MyApp, ], imports: [ BrowserModule, HttpClientModule, HttpModule, IonicModule. Ionic 4 | Make HTTP Calls and Handle Responses Easily Using an Interceptor Last updated on September 16, 2019 Jolly.exe Applications with dynamic data call from REST API to get updated, these calls are mainly of POST or GET type.

ionic 3 Set default requests header from ionic storage, Inside the first part we have built the server for our JSON Web Token Also, we install the Ionic storage package where we will store the 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. ionic start devdacticAuth blank Besides that we also need to include the HttpClientModule inside our module and the Ionic Storage,  Building a JWT authentication flow is one of the basic things most apps have these days, but there are tricky elements that can make or break your app. Today we will dive into the creation of an Ionic JWT app that allows us to login and protect our pages even when accessed as a URL in the browser. We also wanna have a tab bar routing, which is guarded by a login page upfront. We'll not create

Comments
  • Thanks for your reply, but is the native ionic storage not better then localstorage ? (This is what I read from different source and that's the problem, there are a lot of sources and all tell them differently :)
  • Matter of personal choice. In your case Ionic Storage and Local Storage are very similar, almost the same. I will add one more thing to the above answer.
  • Thanks, I tried your code and it works, except the first time I access the page. Then the token is undefined.
  • At which point you are doing setItem? Right after login/moment you get token or later?
  • The token get set after the response of API. When I do a ionic serve (again), the token is the first time unidentifiied even its set in storage. However I must say that I didn't experienced this issue again. Maybe a caching issue with ionic serve ?