Alex
Alex

Reputation: 183

How do I set the authorisation header to a bearer token generated for other API requests

I have created a service that calls to a third party endpoint. I have used their auth endpoint to generate a bearer token which I need to use with other api calls.

Since this is a 3rd party API I'm calling to my target urls and headers are built on a proxy.

Now that I have generated the access_token how can I add this string to the authorisation header?

enter image description here

Component

 showOAuth() {
    this.zebraService.getOAuth()
      .subscribe((data: any) => {
      console.log('Zebra Response: ', data);
      console.log(data.body);
      this.OAuth = data.body;

      this.access_token = this.OAuth.access_token;
      console.log(this.access_token);
      });
  }

Proxy

"/zebraAccessApi": {
  "target": "https://api.com",
  "secure": true,
  "changeOrigin": true,
  "pathRewrite": {
    "^/zebraAccessApi": ""
  },
  "headers": {
    "client_id": "",
    "client_secret": ""
  }
},

"/zebraSetAppLed": {
  "target": "https://api.com/setAppLed",
  "secure": true,
  "changeOrigin": true,
  "pathRewrite": {
    "^/zebraSetAppLed": ""
  },
  "headers": {
    "Content-Type": "application/json",
    "Authorization": ""
  }
}

Service

zebraOAuthUrl = '/zebraAccessApi';
    zebraSetAppLedUrl = '/zebraSetAppLed';

    public getOAuth() {    
        let options = {
            observe: 'response' as 'body',
            response: 'json'
        };
        return this.http.get(this.zebraOAuthUrl, options);
    }

Upvotes: 2

Views: 806

Answers (1)

chriszichrisz
chriszichrisz

Reputation: 567

You could write an interceptor to add the necessary headers:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const token = <YOUR_TOKEN>;

  // if no token add some default stuff or just return the req
  const reqNoToken = request.clone({
    setHeaders: {
      'Content-Type': 'application/json', 
    }
  });
  if (!token) {
    return next.handle(reqNoToken);
  }
  // this is basically where the magic happens
  const req = request.clone({
    setHeaders: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    }
  });
  return next.handle(req).pipe(
    tap((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        console.log(err)
      }
    })
  );
}

An interceptor does what its name suggests, it intercepts your request and in the above case adds the necessary token and headers, or it doesn't if no token is set.

I think you have to alter the function to your needs, but I guess this should be no problem.

Also please read about angular interceptors here, as I don't want to go into full detail about the concept: https://angular.io/api/common/http/HttpInterceptor

Upvotes: 3

Related Questions