PassportJS重定向循环

时间:2013-12-17 10:42:48

标签: javascript node.js coffeescript passport.js restify

以下是我的代码

restify = require("restify")
passport = require("passport")
GoogleStrategy = require("passport-google").Strategy

jsonContentType = (req, res, next) ->
    res.setHeader("content-type", "application/json")
    next(req, res, next)

server = restify.createServer(
    name: "Sparked API"
)

passport.use(new GoogleStrategy({
    returnURL: "http://localhost:8080/auth/google/return"
    realm: "http://localhost:8080/"
}, (id, profile, done) ->
    done()
))

server.use(jsonContentType)

server.get("/", (req, res, next) -> 
    res.send(
        message: "hello world!"
    )
)

server.get("/auth/google", passport.authenticate("google"))

server.get("/auth/google/return", passport.authenticate("google", {
    successRedirect: "/"
    failureRedirect: "/"
}))

server.listen(8080, -> console.log("restify listening on 8080"))

看来即使使用非常简洁的版本,我也会获得重定向循环

server.get("/auth/google/return", passport.authenticate("google", {
    successRedirect: "/"
    failureRedirect: "/"
}))

/是未经身份验证的网址,这是如何导致重定向循环的?我也试过加入

server.use(passport.initialize())
server.use(passport.session())

passport.serializeUser((user, done) ->
  done(null, user)
)

passport.deserializeUser((obj, done) ->
  done(null, obj);
)

但无济于事

1 个答案:

答案 0 :(得分:5)

您的重定向循环正在发生,因为护照无法解析包含许多查询参数的OpenId响应。 Restify有bundled query parser你可以使用。

server.use restify.queryParser()

尽管restify类似于express,但它没有所有的API护照预期。一个主要的res.redirect failureRedirectsuccessRedirect选项is used。您需要手动设置标题和状态,如下所示:

server.get "/auth/google/return", passport.authenticate("google"),
    (req, res, next) ->
        res.header 'Location', '/'
        res.send 302 # redirect status

通过这两个补充,我能够让它在本地工作(gist