【问题标题】:Interceptor for HttpRequests made by aws APIaws API 发出的 HttpRequests 拦截器
【发布时间】:2021-02-05 20:17:22
【问题描述】:

我正在开发一个项目,该项目使用 cognito 作为身份验证服务来保护使用 nodeJS 制作的无服务器 rest 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);
}

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

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

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

编辑: 同样在 app.module.ts 中:

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

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

祝你愉快!

【问题讨论】:

标签: angular amazon-web-services api authentication aws-api-gateway


【解决方案1】:

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

Axios 是一个 JavaScript 库,用于从 node.js 发出 HTTP 请求 或来自浏览器的 XMLHttpRequests,它支持 Promise API 这是 JS ES6 原生的。可以用来拦截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();
}

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
    }
],

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

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

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

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

【讨论】:

  • 即使在一年之后,我也学到了一些东西。谢谢
猜你喜欢
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2018-03-31
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多