默认情况下,如何使Express路由要求身份验证? [英] How to make Express routes require authentication by default?
问题描述
我已经看到了许多示例,这些示例说明了如何向需要限制登录用户身份的某些路由添加身份验证中间件(这意味着默认值是允许任何人访问页面),但是我不知道如何要使所有路由默认情况下都需要登录,并在匿名用户应该可以使用的路由中有选择地选择某些路由.
I've seen many examples of how to add an authentication middleware to certain routes that need to be restricted to logged-in users (implying that the default is to allow anyone to access pages), but I can't tell how to make all routes by default require being logged-in, and selectively choose certain routes among those that should be available to anonymous users.
有什么办法可以使它像这样工作吗?我正在使用Express 4.
Any ways to make it work like this? I'm using Express 4.
推荐答案
我将使用: https://github. com/expressjs/session 用户通过身份验证后,便可以在处理快递路线的控制器中检查有效会话.
I would use: https://github.com/expressjs/session once the user is authenticated then you can check for valid sessions in your controller that handles the route of express.
更新后的答案
这就是我要控制用户登录的方式
This is how I would do the control user logged
/**
* Module dependencies
*/
var express = require('express'),
http = require('http'),
session = require('express-session'),
app = module.exports = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3000);
app.set('trust proxy', 1);
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {
secure: true
}
}));
function checkUserLoggedIn(req, res, next) {
return req.session;
}
/**
* Routes to control by default is logged in with a regular expression
*/
app.get('/user/:use_id/*', function (req, res, next) {
if (checkUserLoggedIn(req)) {
console.log('User logged');
next();
} else {
console.log('error');
}
});
/**
* User Home
*/
app.get('/user/:use_id/home/', function (req, res, next) {
if (checkUserLoggedIn(req)) {
console.log('User logged goes to home');
next();
} else {
console.log('error');
}
});
/**
* Home for user that is actually logged
*/
app.get('/guest/dashboard', function (req, res, next) {
console.log('This is guest dashboard');
});
/**
* Home for user that is actually logged
*/
app.get('/guest/home', function (req, res, next) {
console.log('This is guest home');
});
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
然后运行
$节点app.js
$ node app.js
转到浏览器并访问 http://localhost:3000/home
您定义的用于控制'/*'的正则表达式将获取所有默认路由,然后转到与/home匹配的下一条路由.
The regular expression you defined in to control '/*' is getting all the defaults routing and then is going to the next route that matches, thats /home.
这是一种解决方法,也许有更好,更清晰的方法可以解决此问题.在正则表达式中,您可以控制默认路由的含义以及每种情况的具体含义.
This is one way to do it, may be there is a better and more clear way to fit the issue. In the regular expression you control what you mean with default routes and for each case particular.
这篇关于默认情况下,如何使Express路由要求身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!