由 aws API 制作的 HttpRequest 拦截器

Aym*_*ani 6 authentication api amazon-web-services aws-api-gateway angular

我正在开发一个项目,该项目使用 cognito 作为身份验证服务来保护使用 nodeJS 制作的无服务器休息 API。我已成功关闭未经身份验证的客户端的 API。现在,每当我从 Angular 客户端发出请求时,我都需要在标头中自动注入一个令牌。我尝试的是实现这样的 HttpInterceptor :

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);
}
Run Code Online (Sandbox Code Playgroud)

当使用标准的 Angular HttpClient 发出请求时,这对我来说总是很有效。但现在,当我使用 aws-amplify 包中的 API 向我的 API.Gateway 发出请求时,这些请求无法像这样被拦截。这是我提出请求的方式:

import { API } from 'aws-amplify';
.
.
.
 return API.get('apiName', '/users',{})
Run Code Online (Sandbox Code Playgroud)

而且这些都没有使用 Angular HttpClient。

编辑:也在 app.module.ts 中:

providers : [{
    provide : HTTP_INTERCEPTORS,
    useClass: HttpRequestInterceptor,  --> My interceptor class
    multi   : true,
  }]
Run Code Online (Sandbox Code Playgroud)

有人知道我如何拦截这些对我的 API 网关的请求以注入令牌吗?

祝你玩得开心!

Kes*_*v J 9

使用Axios拦截使用 aws-amplify 包发出的请求,因为 aws-amplify 包使用 Axios 发出请求。

Axios 是一个 Javascript 库,用于从浏览器的 Node.js 或 XMLHttpRequest 发出 HTTP 请求,它支持 JS ES6 原生的 Promise API。它可用于拦截 HTTP 请求和响应,并启用客户端针对 XSRF 的保护。它还具有取消请求的能力。

在本例中,为拦截器创建一个新服务。

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();
}
Run Code Online (Sandbox Code Playgroud)

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
    }
],
Run Code Online (Sandbox Code Playgroud)

此外,我们还可以通过在intercept()方法中使用以下代码来处理错误响应。

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

    return Promise.reject(errorObj.response);
});
Run Code Online (Sandbox Code Playgroud)

PS:我真的很难弄清楚这一点。即使答案已经晚了,我希望它对将来的人有所帮助:)

  • 即使一年后,我还是学到了一些东西。谢谢 (2认同)