首页 > 解决方案 > 跨域Auth0认证

问题描述

我的后端使用 Auth0 验证了以下端点

api.mysite.com/auth/login
api.mysite.com/auth/logout
api.mysite.com/ → returns “logged in” or “logged out”

我的后端是一个快递服务器

另一方面,如果我在 mysite.com 上的前端打开控制台,fetch(‘api.mysite.com’)即使在新选项卡中导航到 api.mysite.com 给我“logged in”,也会返回“logged out”。

我将 https://*.mysite.com 列入“允许的 Web 来源”和“允许的来源”下的白名单,但我无法弄清楚为什么我无法访问我的 API。

提前致谢

在此处输入图像描述

应该注意的是,我在 api.mysite.com/auth/login 使用通用登录

标签: expressauth0

解决方案


这是我的 cors middelware

import { NextFunction, Request, Response } from "express";

const corsMiddleware = (req: Request, res: Response, next: NextFunction) => {
  const allowedDomains = [
    "http://localhost:4200",
    "https://sample.ir",
    "https://sample.ir"
  ];
  if (allowedDomains.indexOf(req.headers.origin) !== -1) {
    const index: number = allowedDomains.indexOf(req.headers.origin);
    res.header("Access-Control-Allow-Origin", allowedDomains[index]);
  }

  res.header("Access-Control-Allow-Headers", "Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Max-Age", "3600");

  // if (req.url.search("public") == -1) {
  //   res.header("content-type", "application/json; charset=utf-8");
  // }

  const method = req.method;
  if (method == "OPTIONS") {
    // res.header("HTTP/1.1 200 OK CORS");
    return res.status(200).json({});
  }
  next();

};

export default corsMiddleware;



推荐阅读