The AuthInterceptor class

In a nutshell, HttpInterceptors are something that we can use to perform modifications to our HTTP requests in a global, centralized way. The most common use case for that pattern is to automatically attach auth information to requests before they're being sent, which is definitely our scenario.

Intercepting HTTP requests has always been possible in AngularJS, yet it has been a missing feature of the new Angular 2+, thus forcing most developers into working, yet unsatisfying workarounds such as the aforementioned HTTP wrappers, helper functions returning custom Headers, and so on. With the release of Angular 4.3, the gap has been filled, thanks to the introduction of the HttpInterceptor interface, which is what we'll use to create our own AuthInterceptor class.

From Solution Explorer, right-click on the /ClientApp/app/services/ folder, add the auth.interceptor.ts TypeScript file, and fill it with the following contents:

import { Injectable, Injector } from "@angular/core";
import { HttpHandler, HttpEvent, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { AuthService } from "./auth.service";
import { Observable } from "rxjs/Observable";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(private injector: Injector) { }

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

var auth = this.injector.get(AuthService);
var token = (auth.isLoggedIn()) ? auth.getAuth()!.token : null;
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
return next.handle(request);
}
}

As we can see, our custom interceptor implements the HttpInterceptor interface and its intercept method, accepting the HttpRequest and HttpHandler parameters; inside the method, we clone the original request--which is immutable, thus can't be altered directly--and add the authorization header containing our token, which we retrieve through the getToken() method of our AuthService class. Note how, once we're done, we pass the request to the next handler in the stack; a great feature of HttpInterceptor is that they can be easily chained, as we'll see in the next paragraph.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.251.57