道歉它是用coffeescript(不是纯粹的js)写的。 我一直在看passport.js,我正在尝试将它包含在一个项目中,这里只是一个简洁的版本。
express = require 'express'
passport = require 'passport'
LocalStrategy = require 'passport-local'
.Strategy
BasicStrategy = require 'passport-http'
app = express()
server = require 'http'
.createServer app
server.listen 3000
app.use express.cookieParser()
app.use express.session
secret: 'abc'
app.use express.json()
app.use express.urlencoded()
app.set 'views', "#{__dirname}/views"
app.set 'view engine', 'jade'
app.locals.pretty = true
app.use passport.initialize()
app.use passport.session()
passport.use new LocalStrategy (username, password, done) ->
if username is 'admin' and password is 'password'
return done null, user =
username: 'admin'
else
return done null, false, message: 'Incorrect username / password'
passport.serializeUser (user, done) ->
done null, user.username
passport.deserializeUser (username, done) ->
done null, user =
username: username
app.get '/login', (req, res) ->
res.render 'login',
title: 'Login'
app.post '/login', passport.authenticate 'local',
successRedirect: '/admin'
failureRedirect: '/login'
app.get '/admin', (req, res) ->
res.render 'admin',
title: 'Admin'
app.get '/devices', (req, res) ->
res.render 'devices',
title: 'Devices'
这是非常基本的,因为本地策略只是检查用户名是'admin'而密码是'password'但是我不确定如何保护'/ admin'和'/ devices'路由?我试过这种事:
app.get '/devices', passport.authenticate('local', {
failureRedirect: '/login'
}, (req, res) ->
res.render 'devices',
title: 'Devices'
但这似乎不起作用..
答案 0 :(得分:3)
如果用户在登录后成功通过身份验证,您可以执行以下操作:
ensureAuthenticated = (req, res, next) ->
if req.isAuthenticated() then return next() else res.send 401
app.get "/devices", ensureAuthenticated, (req, res) ->
res.render 'devices',
title: 'Devices'
答案 1 :(得分:1)
res.send(401)
现在已弃用。
您还可以使用ES6语法:
const ensureAuthenticated = (req, res, next) => req.isAuthenticated() ? next() : res.sendStatus(401);
app.get('/devices', ensureAuthenticated, (req, res) => { ... })