Using an AuthInterceptor Class

From PeformIQ Upgrade
Revision as of 10:08, 24 October 2019 by PeterHarding (talk | contribs) (Created page with " =In app.module.ts= <pre> ... import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; ... ], providers: [ { provide: HTTP_INTERCEPTORS, useClass:...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

In app.module.ts

...
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
...

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



Sample AuthInterceptor Class

In auth-interceptor.ts

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { JwtHelperService } from '@auth0/angular-jwt';
import { environment } from '../environments/environment';

import * as moment from 'moment';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  apiUser = 'xxx@xxx.xxx';
  apiPassword = 'xxxx';
  apiUrlBase = environment.baseUrl;

  // -------------------------------------------------------------------------

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // tslint:disable-next-line: max-line-length

    let token = localStorage.token;

    // let token = '..';
    // ; // you probably want to store it in localStorage or something

    const now = new Date();

    const dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');

    console.log('[intercept]                                   now |' + now + '|');

    const helper = new JwtHelperService();

    const decodedToken = helper.decodeToken(token);

    console.log('[intercept]                          decodedToken |' + decodedToken + '|');

    const expirationDate = helper.getTokenExpirationDate(token);

    const expirationTimestamp = moment(now).format('YYYY-MM-DD HH:mm:ss');

    console.log('[intercept]                   expirationTimestamp |' + expirationTimestamp + '|');

    const isExpired = helper.isTokenExpired(token);

    console.log('[intercept]                             isExpired |' + isExpired + '|');

    if (isExpired) { // Need to get a new token
        token = this.getApiBearerToken();
        console.log('[intercept]                             newToken |' + token + '|');
        localStorage.setItem ('token', token);
    }

    if (!token) {
      return next.handle(req);
    }

    const req1 = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${token}`)
    });

    return next.handle(req1);
  }

  // -----------------------------------------------------------------------

  genarateBasicAuthHash(user: string, password: string)
  {
      const token = user + ':' + password;

      // Should i be encoding this value????? does it matter???
      // Base64 Encoding -> btoa
      const hash = btoa(token);

      return 'Basic ' + hash;
  }

  // -----------------------------------------------------------------------

  getApiBearerToken() {

    console.log('[app.service::getApiBearerToken]');

    const basicAuthHash = this.genarateBasicAuthHash(this.apiUser, this.apiPassword);

    const uri = this.apiUrlBase + '/auth';

    console.log('[getApiBearerToken]                           uri |' + uri + '|');

    const request = new XMLHttpRequest();

    request.open('POST', uri, false);
    request.setRequestHeader('Authorization', basicAuthHash);
    request.send();

    // View request status

    // alert(request.status);

    console.log('[getApiBearerToken]                               |' + request.responseText + '|');

    const json = JSON.parse(request.responseText);

    const newToken = json.token;

    console.log('[getApiBearerToken]                               |' + newToken + '|');

    // return this._http.get(uri).pipe(map(res => res.json()), catchError(this.handleError));

    return newToken;

  } // getApiBearerToken

  // -------------------------------------------------------------------------

}

Problem is XMLHttpRequest() call runs in main thread - needs to be run in a background thread.