Angular5 HttpInterceptor depending on the result of an Observable

前端 未结 2 1805
终归单人心
终归单人心 2021-01-02 18:09

I am trying to implement using Angular5 an HttpInterceptor to inject an Authorization header in all HTTP requests.

I rely on a third party library (ADAL

2条回答
  •  太阳男子
    2021-01-02 18:26

    This code will do the job, the trick is using mergeMap

    import { Injectable, Injector } from '@angular/core';
    import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    import { AdalService } from './adal.service';
    import 'rxjs/add/operator/mergeMap';
    
    @Injectable()
    export class AdalInterceptor implements HttpInterceptor {
    
        constructor(private adal: AdalService) { }
    
        intercept(req: HttpRequest, next: HttpHandler): Observable> {
    
            // if the endpoint is not registered then pass
            // the request as it is to the next handler
            const resource = this.adal.GetResourceForEndpoint(req.url);
            if (!resource) {
                return next.handle(req.clone());
            }
    
            // if the endpoint is registered then acquire and inject token
            let headers = req.headers || new HttpHeaders();
            return this.adal.acquireToken(resource)
                .mergeMap((token: string) => {
                    // if the user is not authenticated then drop the request
                    if (!this.adal.userInfo.authenticated) {
                        throw new Error('Cannot send request to registered endpoint if the user is not authenticated.');
                    }
    
                    // inject the header
                    headers = headers.append('Authorization', 'Bearer ' + token);
                    return next.handle(req.clone({ headers: headers }));
                }
            );
        }
    }
    

提交回复
热议问题