File

libs/oauth/src/lib/interceptor/oauth.interceptor.ts

Index

Methods

Constructor

constructor(oauthService: OauthService)
Parameters :
Name Type Optional
oauthService OauthService No

Methods

intercept
intercept(req: HttpRequest<>, next: HttpHandler)
Parameters :
Name Type Optional
req HttpRequest<> No
next HttpHandler No
Returns : Observable<HttpEvent<>>
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, from } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
import { OauthService } from '../oauth.service';

@Injectable()
export class OauthInterceptor implements HttpInterceptor {
  constructor(private oauthService: OauthService) {}

  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const idpConfigForRequest = this.oauthService.getFirstConfigWithAccessTokenResponsibleForUrl(
      req.url
    );

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

    return from(this.oauthService.refreshTokenIfRequired(idpConfigForRequest?.name)).pipe(
      map(() => {
        const accessToken = this.oauthService.getFirstAvailableAccessTokenForUrl(req.url);
        if (!accessToken) {
          return req;
        }

        const headersWithAuth = req.headers.append('Authorization', `Bearer ${accessToken}`);
        return req.clone({ headers: headersWithAuth });
      }),
      mergeMap((requestWithAuthHeaders) => next.handle(requestWithAuthHeaders))
    );
  }
}

results matching ""

    No results matching ""