Sha*_*oon 8 express angularjs passport.js
我的应用程序使用Express和AngularJS.我正在使用express通过静态来处理角度代码的基本网络搜索.角度代码使用命中由express托管的API端点的服务.我只希望在用户通过身份验证后可以访问API端点.我怎样才能通过PassportJS实现这一目标?
klo*_*ode 19
我已经在github 上传了一个我一直在研究的Angular-Express 项目.
它仍在进行中.我希望它有所帮助.
它使用PassportJ进行用户身份验证,是服务器端授权的基本示例.它演示了如何仅对经过身份验证的用户或仅具有admin角色的用户访问API调用.这是在server/routes.js
调用中间件函数时实现的ensureAuthenticated
,并在ensureAdmin
其中定义server/authentication.js
在routes.js中
// anybody can access this
app.get('/api/test/users',
api.testUsers);
// only logged-in users with ADMIN role can access this
app.get('/api/users',
authentication.ensureAdmin,
api.testUsers);
// only logged-in users can access this
app.get('/api/books',
authentication.ensureAuthenticated,
api.books);
Run Code Online (Sandbox Code Playgroud)
在authentication.js中
ensureAuthenticated: function(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
return res.send(401);
}
},
ensureAdmin: function(req, res, next) {
// ensure authenticated user exists with admin role,
// otherwise send 401 response status
if (req.user && req.user.role == 'ADMIN') {
return next();
} else {
return res.send(401);
}
},
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7067 次 |
最近记录: |