本文介绍了aws API 对 HttpRequests 的拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}

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

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',{})

而且这些没有使用 Angular HttpClient.

And these are not using the Angular HttpClient.

同样在 app.module.ts 中:

EDIT :Also in app.module.ts :

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

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

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

祝你好运!

推荐答案

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

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

Axios 是一个 Javascript 库,用于从 node.js 发出 HTTP 请求或来自浏览器的 XMLHttpRequests,它支持 Promise API这是 JS ES6 原生的.可以用来拦截HTTP请求和响应并启用针对 XSRF 的客户端保护.它也是可以取消请求.

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

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

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()方法中使用以下代码来处理错误响应.

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:我很难弄清楚这一点.甚至认为答案很晚,我希望它可以帮助将来的人:)

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

这篇关于aws API 对 HttpRequests 的拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 20:34