我正在开发一个使用 Azure 静态 Web 应用程序产品的项目。我已经实现了一个由 azure-function-express 提供支持的 Passport.js 身份验证策略,它在 Authentication 标头中接收 JWT,验证 JWT,并返回用户信息。
我的系统在本地工作,但在部署中返回 401 未授权。
在部署中进行测试时,Application Insights 推断资源由于 CORS 问题而被阻止,但未指定哪个资源。尽管存在 CORS 问题,该函数似乎仍会执行,但即使测试帐户信息正确,也会返回 401。
是否有人有此问题的经验或知道如何识别 CORS 阻止了哪个资源?
Azure 实时分析——抱歉,为了便于阅读,这些内容无法完全展开
CORS 消息扩展
该请求有一个原始标头:“https://icy-plant-mysiteID.centralus.azurestaticapps.net”。
CORS 策略执行失败。
请求来源https://icy-plant-mysiteID.centralus.azurestaticapps.net没有访问资源的权限。
GetUserFromJwt Azure 函数
const passport = require('passport');
const createHandler = require("azure-function-express").createHandler;
const express = require("express");
const app = express();
const mongooseHelper = require('../config/mongoose');
// Configure passport, express
require('../config/passport')(passport);
require('../config/express')(app, passport);
mongooseHelper.connectToMongoose("GetUserIdFromJwt");
app.get('/api/getUserIdFromJwt', passport.authenticate('jwt', { session: false }), (req, res, next) => {
res.status(200).json(req.user)
});
// Binds the express app to an Azure Function handler
module.exports = createHandler(app);
API 调用(在检索 JWT 时从客户端调用)
export const getUserIdFromJwt = (jwt) => {
return new Promise((resolve, reject) => {
axios({
url: '/api/getUserIdFromJwt',
method: 'GET',
headers: { "Authorization": jwt }
}).then((res) => {
resolve(res.data)
}).catch((err) => {
reject(console.log("An error occured getting the User from JWT: " + err));
});
})
}
护照配置
// Configure Passport
const User = require('../models/UserModel');
const JwtStrat = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const PUB_KEY = **MY KEY**;
const passportOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: PUB_KEY,
algorithms: ['OurAlgorithm'],
passReqToCallback: true
}
const strat = new JwtStrat(passportOptions, (req, payload, done) => {
User.findOne({ _id: payload.sub })
.then((user) => {
if (user) {
// Send id as User. Do not send personal info here.
req.user = {id: payload.sub, role: payload.role};
return done(null, req.user);
} else {
return done(null, false);
}
})
.catch(err => {
done(err, null)
});
});
module.exports = (passport) => {
passport.use(strat);
}
快速配置
const express = require('express')
const cors = require('cors');
module.exports = (app, passport) => {
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use(passport.initialize());
}