Interceptor for HttpRequests made by aws API

Viewed 1160

I'm working on a project that uses cognito as an auth service to secure a serverless rest API made using nodeJS. I've successfully closed the API for non-authenticated clients. I now need to automatically inject a token in the header whenever i make a request from my Angular client. What i tried is implementing an HttpInterceptor like this :

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


    req = req.clone({
        setHeaders: {
          'Content-Type' : 'application/json; charset=utf-8',
          'Accept'       : 'application/json',
              'Authorization': `${this.authService.userToken}`,
              //#endregion
          },
          
        })
  

  return next.handle(req);
}

This always worked fine for me when using the standard angular HttpClient to make requests. But now as i'm using API from aws-amplify package to make request to my API.Gateway, these requests can't get intercepted like this. Here's how i make requests :

import { API } from 'aws-amplify';
.
.
.
 return API.get('apiName', '/users',{})

And these are not using the Angular HttpClient.

EDIT : Also in app.module.ts :

providers : [{
    provide : HTTP_INTERCEPTORS,
    useClass: HttpRequestInterceptor,  --> My interceptor class
    multi   : true,
  }]

Anyone got an idea of how i can intercept these request to my API Gateway to inject the token?

Have a nice one !

1 Answers

Use Axios for intercepting requests made using the aws-amplify package because the aws-amplify package uses Axios to make its requests.

Axios is a Javascript library used to make HTTP requests from node.js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. It can be used to intercept HTTP requests and responses and enables client-side protection against XSRF. It also has the ability to cancel requests.

In this case, create a new service for the Interceptor.

In axios-interceptor.service.ts,

import { Injectable } from '@angular/core';
import axios from 'axios';

@Injectable({providedIn: 'root'})
export class AxiosInterceptorService {
    intercept() {
        axios.interceptors.request.use(request => {
            request.headers['Content-Type'] = 'application/json; charset=utf-8';
            request.headers.Accept = 'application/json';
            request.headers.Authorization = `${userToken}`;
            return request;
        });
    }
}

export function AxiosConfigFactory(axiosIntercept: AxiosInterceptorService): any {
  return () => axiosIntercept.intercept();
}

In app.module.ts,

import { APP_INITIALIZER, NgModule } from '@angular/core';
import { AxiosConfigFactory, AxiosInterceptorService } from './axios-interceptor-service.service';

providers: [
    {
        provide: APP_INITIALIZER,
        useFactory: AxiosConfigFactory,
        deps: [AxiosInterceptorService],
        multi: true
    }
],

Furthermore, we can also handle error responses by using the below code inside the intercept() method.

axios.interceptors.response.use(response => {
      return Promise.resolve(response);
    }, errorObject => {

    return Promise.reject(errorObj.response);
});

PS: I had a really hard time figuring this out. Even thought the answer is late, I hope it helps someone in the future :)

Related