Passport Js处理HTTP API的访客身份验证

时间:2014-09-14 10:13:14

标签: node.js express passport.js

这是我的代码:

passport = require 'passport'
BasicStrategy = require('passport-http').BasicStrategy

passport.use new BasicStrategy((username, pwd, done) ->
  console.log arguments
  if pwd is "1234" and username is "Foo"
    done undefined, {
      username: "Foo"
      role: "admin"
    }
  else done()
)


express = require("express")
app = express()

app.use express.logger()
app.use passport.initialize()
app.use passport.authenticate("basic", session: false)

app.get '/', (req, res) -> res.send req.user

但是这种方式只有在用户使用标题进行身份验证时才有效。如果未指定授权标头,我只需获得401' /'。有没有办法让认证可选?或者用一种安静的方式来指定授权来说“嗨,我是客人"?

1 个答案:

答案 0 :(得分:1)

passport-http中间件will call fail() if Authorization header is missing

您可以编写自己的身份验证策略,或者分叉修改passport-http,或添加一个中间件,如果丢失则添加标头,即。

GUEST = "Basic #{new Buffer('guest:guest').toString('base64')}"
app.use (req, res, next) ->
  req.headers['authorization'] = GUEST unless req.headers['authorization']
  next()

在致电app.use(passport...)之前,您需要添加此中间件。然后在策略中你可以做到,例如。

passport.use new BasicStrategy (user, pass, done) ->
  if user == pass == 'guest'
    done null, {username: 'Guest'}
  else
    ...