[英]How to set up CORS and JWT token validation with ExpressJs based on website
所以基本上,我有兩個具有不同子域的網站。 第一個不需要 JWT 令牌驗證,但第二個需要驗證。
僅當來源為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 驗證作為中間件,我嘗試檢查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');
}
};
第一個站點www.welcome.com
使用 Nextjs(服務器端渲染)構建,第二個站點使用 React create app(客戶端渲染)構建。 因此,當我檢查req.get('origin')
的 react create app 請求時,它工作正常,但對於來自 nextjs 應用程序的請求,它是未定義的。
您應該能夠使用req.hostname
來獲取您收到請求的主機。 您可以在文檔中查看請求 object 的其他屬性: http://expressjs.com/en/api.html#req
最后,我解決了這個問題。 問題出在 NextJs 上,我正在使用getserversideprops
進行服務器端請求(服務器到服務器時沒有 CORS),所以我轉向基本客戶端請求,然后它工作正常。 我可以訪問req.origin
所以我可以檢查來源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.