简体   繁体   English

如何使用基于网站的 ExpressJs 设置 CORS 和 JWT 令牌验证

[英]How to set up CORS and JWT token validation with ExpressJs based on website

So basically, I have two websites with different subdomain.所以基本上,我有两个具有不同子域的网站。 The first one doesn't need JWT Token validation but the second needs validation.第一个不需要 JWT 令牌验证,但第二个需要验证。

How to use the app.use(authorization) only when the origin is https://app.website.com ?仅当来源为https://app.website.com时如何使用app.use(authorization)

import cors from 'cors';

if (process.env.NODE_ENV === 'development') {
  app.use(cors());
} else {
  const whitelist = ['https://www.website.com', 'https://app.website.com'];
  app.use(
    cors({
      origin: function (origin, callback) {
        if (origin && whitelist.indexOf(origin) !== -1) {
          return callback(null, true);
        }
        return callback(new Error('Forbidden'), false); 
      },
      optionsSuccessStatus: 204
    })
  );
  app.use(authorization);
}

JWT validation as a middleware, I tried to check req.get('origin') but it's undefined.. JWT 验证作为中间件,我尝试检查req.get('origin')但它未定义..

import admin from '../helpers/firebase.helper';

const authorization = async (
  req,
  res,
  next
): Promise<void> => {
  if (req.headers?.authorization?.startsWith('Bearer ')) {
       const idToken = req.headers.authorization.split('Bearer ')[1];
    try {
      const decodeToken = await admin.auth().verifyIdToken(idToken);
      req.current = decodeToken;
      next();
    } catch (err) {
      res.status(StatusCodes.UNAUTHORIZED).send('UnAuthorized');
    }
  } else {
    res.status(StatusCodes.UNAUTHORIZED).send('UnAuthorized');
  }
};

The first site www.welcome.com is built with Nextjs (server side rendering) and the second one with React create app (client side rendering).第一个站点www.welcome.com使用 Nextjs(服务器端渲染)构建,第二个站点使用 React create app(客户端渲染)构建。 So when I check req.get('origin') for react create app request it's working fine, but for the request which comes from the nextjs app it's undefined.因此,当我检查req.get('origin')的 react create app 请求时,它工作正常,但对于来自 nextjs 应用程序的请求,它是未定义的。

Diagram图表在此处输入图像描述

You should be able to use req.hostname to get the host on which you received the request.您应该能够使用req.hostname来获取您收到请求的主机。 You can check other properties of the request object in the docs: http://expressjs.com/en/api.html#req您可以在文档中查看请求 object 的其他属性: http://expressjs.com/en/api.html#req

Finally, I solved the problem.最后,我解决了这个问题。 The problem was with NextJs, I was doing a server side request with getserversideprops (no CORS when server to server), so I move to a basic client request, then it's works fine.问题出在 NextJs 上,我正在使用getserversideprops进行服务器端请求(服务器到服务器时没有 CORS),所以我转向基本客户端请求,然后它工作正常。 I have access to req.origin so I can check the origin.我可以访问req.origin所以我可以检查来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM