仅在将 Auth0 令牌附加到请求时从 api gatweway 获取 CORS 错误

问题描述 投票:0回答:0

所以我正在尝试在 AWS 中托管一个完整的堆栈 Web 应用程序。我有一个有角度的前端,位于云端后面的 s3 存储桶中,并使用来自 route53 的域。在后端,我有一个位于 api 网关后面的 typescript express 项目。我正在使用 auth0 进行身份验证以及他们在其网站上提供的示例前端/后端应用程序。我将在这里链接它们: https://github.com/auth0-developer-hub/spa_angular_typescript_hello-world https://github.com/auth0-developer-hub/api_express_typescript_hello-world

当我发出未被拦截器命中的请求时,它们会起作用,但是当我尝试被拦截器修改的请求时(当我使用 auth0 登录时),我将收到以下错误: “从来源‘https://website.link’访问‘https://api-gateway.com/dev/api/messages/protected’的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。”

下面auth.module中的拦截器代码:

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AuthModule, AuthHttpInterceptor } from '@auth0/auth0-angular';
import { environment as env } from '../environments/environment';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SharedModule } from './shared';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    SharedModule,
    HttpClientModule,
    AuthModule.forRoot({
      ...env.auth0,
      httpInterceptor: {
        allowedList: [`${env.api.serverUrl}/api/messages/admin`, `${env.api.serverUrl}/api/messages/protected`],
        //allowedList: [`${env.api.serverUrl}/api/messages/admin`],
      },
    }),
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthHttpInterceptor,
      multi: true,
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

下面是来自 express 后端的我的 index.ts,我在其中明确允许拦截器附加的“授权”标头。我已经确认它传递的令牌也是有效的。

import cors from "cors";
import * as dotenv from "dotenv";
import * as awsServerlessExpress from 'aws-serverless-express';
import express from "express";
import helmet from "helmet";
import nocache from "nocache";
import { messagesRouter } from "./messages/messages.router";
import { errorHandler } from "./middleware/error.middleware";
import { notFoundHandler } from "./middleware/not-found.middleware";

dotenv.config();

if (!(process.env.PORT && process.env.CLIENT_ORIGIN_URL)) {
  throw new Error(
    "Missing required environment variables. Check docs for more info."
  );
}

const PORT = parseInt(process.env.PORT, 10);
const CLIENT_ORIGIN_URL = process.env.CLIENT_ORIGIN_URL;

const app = express();
const apiRouter = express.Router();

app.use(express.json());
app.set("json spaces", 2);

app.use(
  helmet({
    hsts: {
      maxAge: 31536000,
    },
    contentSecurityPolicy: {
      useDefaults: false,
      directives: {
        "default-src": ["'none'"],
        "frame-ancestors": ["'none'"],
      },
    },
    frameguard: {
      action: "deny",
    },
  })
);

app.use((req, res, next) => {
  res.contentType("application/json; charset=utf-8");
  next();
});
app.use(nocache());

app.use(
  cors({
    origin: CLIENT_ORIGIN_URL,
    methods: ["GET", "POST", "PUT", "DELETE"],
    allowedHeaders: ["Authorization", "Content-Type"],
    maxAge: 86400,
  })
);

app.use("/api", apiRouter);
apiRouter.use("/messages", messagesRouter);

app.use(errorHandler);
app.use(notFoundHandler);

// create serverless express
const server = awsServerlessExpress.createServer(app);

// export the handler function for AWS Lambda
export const handler = (event: any, context: any) => awsServerlessExpress.proxy(server, event, context);

我尝试了各种方法,例如在路由上设置“Access-Control-AllowOrigin”标头,但仍然没有用,如下所示:

messagesRouter.get("/protected", validateAccessToken, (req, res) => {
  res.set("Access-Control-Allow-Origin", CLIENT_ORIGIN_URL);
  try {
    logger.info(JSON.stringify(req.auth));
    logger.info(`Token: ${JSON.stringify(req.auth?.token)}`)
    //console.log(req.auth?.token)
    const message = getProtectedMessage();
  
    res.status(200).json(message);
  }
  catch (err){
    console.log(err);
    res.status(500).json('Error')
  }
});

我还在 index.ts 中尝试了各种 CORS 配置,如下所示:

app.use(cors());
app.use(cors({
  origin: CLIENT_ORIGIN_URL,
  methods: ["GET", "POST", "PUT", "DELETE"],
  allowedHeaders: ["Authorization", "Content-Type"],
  credentials: true,
}));

这些导致了同样的错误

angular typescript amazon-web-services express auth0
© www.soinside.com 2019 - 2024. All rights reserved.