Home > database >  How to Send Different Header with different token in angular interceptor
How to Send Different Header with different token in angular interceptor

Time:10-16

Hi I have a angular interceptor where i am passing token to each server request but sometimes i need to send request to different server with different token how to achieve it in same code.

export class JwtInterceptor implements HttpInterceptor {
constructor(private accountService: AccountService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    const account = this.accountService.accountValue;
    const isLoggedIn = account?.token;
    const isApiUrl = request.url.startsWith(environment.apiUrl);
    if (isLoggedIn && isApiUrl) {
        request = request.clone({
            setHeaders: { Authorization: `Bearer ${account.token}` }
        });
    }

    return next.handle(request);
}

}

here I need to send different token for different server how to do it

CodePudding user response:

Here is an example based on hostname, basically trigger the custom configuration based on hostname Working example is here

Parse the url in its tokens using URL

const url = req.url;
const hostname = new URL(url).hostname;

Then trigger the action using the hostname and switch case

switch (hostname) {
  case Hostname['meowfacts.herokuapp.com']:
    console.log('apply custom interceptor based on hostname - CAT');
    break;
  case Hostname['date.nager.at']:
    console.log('apply custom interceptor based on hostname - HOLIDAY');
    break;
}

You can use an enum to classify hostnames:

export enum Hostname {
  ['meowfacts.herokuapp.com'] = 'meowfacts.herokuapp.com',
  ['date.nager.at'] = 'date.nager.at'
}
export class JwtInterceptor implements HttpInterceptor {
  constructor(private accountService: AccountService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const account = this.accountService.accountValue;
    const isLoggedIn = account?.token;

    const url = request.url;
    const hostname = new URL(url).hostname;

    console.log('url', url);
    console.log('hostname', hostname);

    switch (hostname) {
      case Hostname['meowfacts.herokuapp.com']:
        console.log(
          'here apply custom interceptor behavior based on hostname - CAT'
        );
        /* request = request.clone({
           setHeaders: { Authorization: `Bearer ${account.token}` },
         }); */
        break;
      case Hostname['date.nager.at']:
        console.log(
          'here apply custom interceptor behavior based on hostname - HOLIDAY'
        );
        /* request = request.clone({
           setHeaders: { Authorization: `Bearer ${account.token}` },
         }); */
        break;
    }
    return next.handle(request);
  }
}

CodePudding user response:

let access_token = tokenResponse.access_token;

const { url } = request;
if (url.startsWith(environment.API1)) {
  access_token = this.accountService.tokenResponses[environment.API1]?.access_token;
} else if (url.startsWith(environment.API2)) {
  access_token = this.accountService.tokenResponses[environment.API2]?.access_token;
} else if (url.startsWith(environment.API3)) {
  access_token = this.accountService.tokenResponses[environment.API3]?.access_token;
}

if (!access_token) {
  return throwError(() => new Error('No authorization token found'));
}

request = request.clone({
  setHeaders: {
    Authorization: `Bearer ${access_token}`
  }
});
  • Related