PassportJS redirect loop

爷,独闯天下 提交于 2019-12-13 14:06:32

问题


Below is the code I have

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"))

It appears I am getting a redirect loop even with a very cut down version

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

/ is unauthenticated URL, how is this causing a redirect loop? I also tried adding in

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

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

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

but to no avail


回答1:


Your redirect loop is happening because passport can't parse the OpenId response which includes a number of query params. Restify has a bundled query parser you can use.

server.use restify.queryParser()

Although restify is similar to express, it does not have all of the APIs passport expects. A major one is res.redirect which is used for the failureRedirect and successRedirect options. You'll need to set the header and status manually like so:

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

With those two additions, I was able to get it working locally (gist)



来源:https://stackoverflow.com/questions/20631996/passportjs-redirect-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!