Angular 7 interceptor get local storage value and add to header

Asked
Active3 hr before
Viewed126 times

6 Answers

angularvaluelocalstorageheaderinterceptor
90%

requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection,,To add or overwrite these defaults, simply add or remove a property from these configuration objects

Example_snippet/controller/utility/_angular.js/ // Simple GET request example:. . .
// Simple GET request example:
$http({
   method: 'GET',
   url: '/someUrl'
}).then(function successCallback(response) {
   // this callback will be called asynchronously
   // when the response is available
}, function errorCallback(response) {
   // called asynchronously if an error occurs
   // or server returns response with an error status.
});
Step 2 continued with $http.get('/someUrl', config).. . .
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
Step 3 continued with $httpBackend.expectGET(...); $. . .
$httpBackend.expectGET(...);
$http.get(...);
$httpBackend.flush();
Step 4 continued with module.run(function($http) { . . .
module.run(function($http) {
   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
});
Step 5 continued with var req = { method: 'POST', . . .
var req = {
   method: 'POST',
   url: 'http://example.com',
   headers: {
      'Content-Type': undefined
   },
   data: {
      test: 'test'
   }
}

$http(req).then(function() {
   ...
}, function() {
   ...
});
Step 6 continued with function appendTransform(defau. . .
function appendTransform(defaults, transform) {

   // We can't guarantee that the default transformation is an array
   defaults = angular.isArray(defaults) ? defaults : [defaults];

   // Append the new transformation to the defaults
   return defaults.concat(transform);
}

$http({
   url: '...',
   method: 'GET',
   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
      return doTransform(value);
   })
});
Step 7 continued with // register the interceptor as. . .
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
   return {
      // optional method
      'request': function(config) {
         // do something on success
         return config;
      },

      // optional method
      'requestError': function(rejection) {
         // do something on error
         if (canRecover(rejection)) {
            return responseOrNewPromise
         }
         return $q.reject(rejection);
      },

      // optional method
      'response': function(response) {
         // do something on success
         return response;
      },

      // optional method
      'responseError': function(rejection) {
         // do something on error
         if (canRecover(rejection)) {
            return responseOrNewPromise
         }
         return $q.reject(rejection);
      }
   };
});

$httpProvider.interceptors.push('myHttpInterceptor');

// alternatively, register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
   return {
      'request': function(config) {
         // same as above
      },

      'response': function(response) {
         // same as above
      }
   };
});
Step 8 continued with ['one','two']. . .
['one', 'two']
Step 9 continued with )]}', ['one','two']. . .
)]
}
', ['one', 'two']
load more v
88%

Example_snippet/controller/utility/_angular.js/ // src/app/auth/auth.service.t. . .
// src/app/auth/auth.service.ts

import { Injectable } from '@angular/core';
import decode from 'jwt-decode';

@Injectable()
export class AuthService {  
  public getToken(): string {
    return localStorage.getItem('token');
  }  

	public isAuthenticated(): boolean {    
      // get the token
      const token = this.getToken();    
      // return a boolean reflecting 
      // whether or not the token is expired
      return tokenNotExpired(null, token);  
    }
}

// src/app/auth/token.interceptor.ts
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

// src/app/app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor';

@NgModule({  bootstrap: [AppComponent],
          	 imports: [...],
			 providers: [
                       { 
                       provide: HTTP_INTERCEPTORS,
                       useClass: TokenInterceptor,
                       multi: true   
                       }  
          ]})
export class AppModule {}
load more v
72%

Now, let’s return an observable of the authorization token string, if it is not expired:,Next, we need to add the functionality to fetch the token and check if it’s expired, If it’s expired, we are going to refresh it and return the new token

Example_snippet/controller/utility/_angular.js/ $ npm install @auth0/angular-j. . .
$ npm install @auth0 / angular - jwt
load more v
65%

This is my code from my HttpClient interceptor class:,The headers are correct and the call to ,get works fine by itself

Example_snippet/controller/utility/_angular.js/ getAuth(){ return this.l. . .
getAuth() {

   return this.local.get("UserName")
      .then(res => {
         this.user = res;

         return this.local.get("Token").then(res => this.session = res);
      });
}
get(url) {

   let headers = new Headers({
      'Accept': 'application/json',
      'Content-Type': 'application/json; charset=utf-8'
   });
   let params = new URLSearchParams('format=json');

   this.getAuth().then(() => {

      var authHeader = 'Basic ' + this.encode(this.user + ':{SessionToken}' + this.session);
      headers.append('Authorization', authHeader);

      return this.http.get(url, {
         headers: headers,
         search: params
      });
   });
}
Step 2 continued with getTodos(id){ var url: strin. . .
getTodos(id) {
   var url: string = this.global.APIUrl + "/" + id;

   return this.httpClient.get(url)
      .map((res) => res.json());
}
load more v
75%

Angular interceptors help us to set authorization header to each http request and handle 401 unauthorized access status code,JWT allow us to do token-based authentication,Controller or action method which mark with Authorize attribute, they allow only the authenticated user to access, You can view or download source code from the top of the article,,In this post, I will explain how to create application using Angular 6 app with ASP

Example_snippet/controller/utility/_value.js/ <dotnet new angular –n Tokenb. . .
 < dotnet new angular– n TokenbasedAuthentication
load more v
40%

Local storage value display only null, because interceptor called the very first time

Example_snippet/controller/utility/_value.js/ (data.access_token).subscribe(. . .
(data.access_token).subscribe((response) => {
   // If you subscribe to access_token from some where do this
   const accessToken = response;
   // If your accessToken is not a string and if it object, do stringify other wise add the access token directly to localstorage.
   this.localStorage.setItem("ibAccessToken", JSON.stringify(accessToken));
})
30%