我正在编写一个基于Express.js的应用程序,同时使用Everyauth进行身份验证。
为了初始化everyauth,我使用以下代码:
app.use(everyauth.middleware());
我想为特定路由绕过身份验证。 具体来说,我注意到findUserById在每个请求中都被调用,我想跳过某些路由(例如,/getImage无需身份验证)。
这是否可能?
您可以手动包装everyauth.middleware()
回调函数。
var auth = everyauth.middleware();
app.use(function(req, res, next) {
if (shouldAuthRequest(req)) {
// call auth, as if it was part of the route
auth(req, res, next);
} else {
// ignore auth
next();
}
});
everyauth.middleware
必须使用Express的app
对象进行调用。因此,您可以通过以下方式创建包装后的中间件:var my_auth_middleware = function(app) {
var auth = everyauth.middleware(app);
// a custom middleware wrapping everyauth
var middleware = function(req, res, next) {
if (shouldAuthRequest(req)) {
// go through the everyauth middleware
auth(req, res, next);
} else {
// bypass everyauth
next();
}
};
// these allow the middleware to be "mounted" by Express
middleware.set = true;
middleware.handle = middleware;
middleware.emit = auth.emit;
// return our custom middleware
return middleware;
};
app.use(my_auth_middleware(app));