typescript 仅当将Auth0令牌附加到请求时从API gatweway获取CORS错误

y1aodyip  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(114)

因此,我尝试在AWS中托管一个全栈Web应用程序。我有一个角形前端位于cloudfront后面的s3 bucket中,并使用route 53的域。在后端,我有一个位于API网关后面的typescript express项目。我使用auth 0进行身份验证,并使用他们在网站上提供的示例前端/后端应用程序。我将在这里链接它们:https://github.com/auth0-developer-hub/spa_angular_typescript_hello-worldhttps://github.com/auth0-developer-hub/api_express_typescript_hello-world
当我发出的请求没有被拦截器命中时,它们会工作,但是当我尝试被拦截器修改的请求时(当我使用auth 0登录时),我会得到下面的错误:“CORS策略已阻止从源'https://www.example.com'访问位于'https://api-gateway.com/dev/api/messages/protected'的XMLHttpRequestwebsite.link:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'标头。”
下面的auth.模块中的拦截器代码:

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,在这里我显式地允许拦截器附加的“Authorization”头。我已经确认它传递的令牌也是有效的。

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

这些导致了相同的错误
编辑:包括我从下面的terraform的cloudfront配置:

resource "aws_cloudfront_distribution" "website_distribution" {
  origin {
    domain_name = aws_s3_bucket.frontend_bucket.bucket_regional_domain_name
    origin_id   = aws_s3_bucket.frontend_bucket.id

    s3_origin_config {
      origin_access_identity = aws_cloudfront_origin_access_identity.oai.cloudfront_access_identity_path
    }
  }

  default_cache_behavior {
    allowed_methods  = ["GET", "HEAD"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = aws_s3_bucket.frontend_bucket.id
    forwarded_values {
      query_string = false
      cookies {
        forward = "none"
      }
    }

    viewer_protocol_policy = "redirect-to-https"
    min_ttl                = 0
    default_ttl            = 3600
    max_ttl                = 86400
  }

  restrictions {
    geo_restriction {
      restriction_type = "none"
      locations        = []
    }
  }

  viewer_certificate {
    acm_certificate_arn            = aws_acm_certificate.cert.arn
    ssl_support_method             = "sni-only"
    minimum_protocol_version       = "TLSv1.2_2018"
    cloudfront_default_certificate = false
  }

  custom_error_response {
    error_code            = 403
    response_page_path    = "/index.html"
    response_code         = "200"
    error_caching_min_ttl = 300
  }

  enabled             = true
  is_ipv6_enabled     = true
  http_version        = "http2"
  price_class         = "PriceClass_100"
  default_root_object = "index.html"
  aliases             = [var.domain_name[terraform.workspace], "www.${var.domain_name[terraform.workspace]}"]
}
zengzsys

zengzsys1#

为了从Cloudfront访问API Gateway(当您发出https://cloudfront-host/api/endpoint时发生),您需要定义除S3之外的另一个源,即API网关。
您可以通过Postman或API Gateway直接访问的原因是因为Cloudfront是阻止请求的人。您还需要设置ordered_cache_behavior,以便Cloudfront可以将请求代理到您的自定义源。这与Angular中的proxy.conf.json非常相似,如果您的所有api端点都遵循/api/<endpoint>模式,那么你的有序缓存行为将把对/api/*的请求路由到API网关。
在新的origin定义中,你应该使用custom_origin_config而不是s3_origin_config。另外阅读ordered_cache_behavior,你可能需要调整它。

resource "aws_cloudfront_distribution" "website_distribution" {
  origin {
    domain_name = aws_s3_bucket.frontend_bucket.bucket_regional_domain_name
    origin_id   = aws_s3_bucket.frontend_bucket.id

    s3_origin_config {
      origin_access_identity = aws_cloudfront_origin_access_identity.oai.cloudfront_access_identity_path
    }
  }

  origin {
    domain_name = <>
    origin_id   = <some_id>

    custom_origin_config {
      ...
    }
  }

  ordered_cache_behavior {
    path_pattern     = "/api/*"
    ...
    target_origin_id = <some_id>
    ...
  }

...

相关问题