Ada*_*ean 3 node.js express passport.js
我正在将 Express 和 Passport 用于 Node.js API 应用程序,我可以通过传递{session:false}到来禁用会话passport.authenticate,但是有没有一种方法可以在一个地方执行此操作,这样我就不会重复 600 次?
var app = express();
app.configure(function() {
app.use(express.bodyParser());
app.use(passport.initialize());
});
app.get('/users', passport.authenticate('hash', {session:false}), controllers.users.getAll);
app.get('/users/me', passport.authenticate('hash', {session:false}), controllers.users.getCurrentUser);
// and so on...
Run Code Online (Sandbox Code Playgroud)
如果我能做到,那就太好了:
app.donotuse(sessions).thanks();
Run Code Online (Sandbox Code Playgroud)
只需将结果保存在一个变量中并重新使用它:
var PassportAuthenticateMiddleware = passport.authenticate('hash', {session:false});
...
app.get('/users', PassportAuthenticateMiddleware, controllers.users.getAll);
app.get('/users/me', PassportAuthenticateMiddleware, controllers.users.getCurrentUser);
Run Code Online (Sandbox Code Playgroud)
(或者按照@hexacyanide 的建议进行操作,并在全局范围内使用中间件,如果这是您的设置中的一个选项)
或者,您可以使用类似于以下内容的内容:
app.all('/users*', passport.authenticate('hash', {session:false}));
app.get('/users', controllers.users.getAll);
app.get('/users/me', controllers.users.getCurrentUser);
Run Code Online (Sandbox Code Playgroud)
这将过滤所有请求(而不是.all您也可以使用.get),其 URL 以/users通过身份验证中间件运行。
| 归档时间: |
|
| 查看次数: |
4463 次 |
| 最近记录: |