我正在尝试为我的(非常简单的)CRUD 应用程序实施身份验证步骤。所以这就是想法:连接到 localhost:8000/ 时,您需要单击登录按钮,这将提示您使用 Microsoft 帐户登录。然后您应该被重定向到 localhost:8000/feed。但它只是将我重定向到 localhost:8000。第二个问题是,我可以看到 MongoDB 存储了一个 Cookie。如果我访问 localhost:8000/auth/logout 它会删除它。所以它有效。但我仍然无法访问 localhost:8000/feed,因为 ensureAuth 不会让我访问。
确保身份验证:
module.exports = {
ensureAuth: function(req, res, next){
console.log("Executing ensureAuth function")
if(req.isAuthenticated()){
console.log("Is authenticated")
return next()
}else{
console.log("ensureAuth failed")
res.redirect("/")
}
},
ensureGuest: function(req, res, next){
if(!req.isAuthenticated()){
return next()
}else{
res.redirect("/feed")
}
}
}
认证/登录路径:
router.get('/login',
function(req, res, next) {
passport.authenticate('azuread-openidconnect',
{
response: res,
resourceURL: config.resourceURL,
customState: 'my_state',
failureRedirect: '/'
}
)(req, res, next);
},
function(req, res) {
console.log('Login was called in the Sample');
res.redirect('/feed');
});
认证/注销路线:
router.get('/logout', function(req, res){
req.session.destroy(function(err) {
req.logOut();
res.redirect(config.destroySessionUrl);
});
});
进料路线:
const express = require("express")
const router = express.Router()
const feedController = require("../controllers/feed")
const { ensureAuth, ensureGuest } = require("../middleware/auth")
router.get("/", ensureAuth, feedController.getContent)
router.post("/postScream", feedController.postScream)
module.exports = router
特快专场:
app.use(
session({
secret: 'foo',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
)
如果您需要大量代码,请联系我。我将不胜感激任何形式的支持。