2012-12-02 11 views
8

我正在使用passport.js來驗證用戶身份。我希望能夠傳遞從用戶收集的用戶名,該用戶名將到達認證過程的末尾,以便在創建用戶時(如果它尚不存在)我可以存儲用戶名。我試過這個:如何通過我的passport.js鏈傳遞參數?

app.get("/auth/google", function(request, response) 
{ 
    console.log(request.query.username); 

    passport.authenticate("google", 
    { 
     scope: 
     [ 
      "https://www.googleapis.com/auth/userinfo.profile", 
      "https://www.googleapis.com/auth/userinfo.email" 
     ] 
    })(request, response); 
}); 

app.get("/auth/google/callback", function(request, response) 
{ 
    console.log(request.query.username); 

    passport.authenticate("google", 
    { 
     successRedirect: "/", 
     failureRedirect: "htm/error" 
    })(request, response); 
}); 

對/ auth/google的調用打印用戶名,但回調打印未定義。即使我可以獲得回撥用戶名,我仍然不確定如何將其用於Google策略。那麼我是否必須制定自己的策略才能實現這一目標?

回答

7

您可以通過一個狀態對象passport.authenticate,像這樣:

passport.authenticate("google", 
{ 
    scope: 
    [ 
     "https://www.googleapis.com/auth/userinfo.profile", 
     "https://www.googleapis.com/auth/userinfo.email" 
    ], 
    state: request.query.username 
})(request, response); 

您可以通過req.query.state訪問的狀態。

用戶名應該是一個字符串,而不是一個對象。如果您想在該狀態下存儲對象,請先撥打JSON.stringify,然後在回調中對其進行解析。

1

對於任何使用OpenID的人來說,req.query似乎被OpenId查詢參數覆蓋,因此無法直接傳遞。但是,您可以將變量附加到req.session。

router.get('/auth/social', (req, res, next) => { 
    req.session.foo = req.query.foo; 
    next(); 
}, passport.authenticate('social')); 

,不要忘了,包括在戰略選擇的passReqToCallback標誌:

{ 
    passReqToCallback: true, 
    returnURL: config.app.returnUrl, 
    realm: config.app.realm, 
    apiKey: config.app.apiKey 
} 
+0

這可能是會議和餅乾也被一個OpenID戰略覆蓋(https://github.com/liamcurry /護照蒸汽)?我試過你的解決方案,但是'req.session.foo'在回調路由中是'undefined'。 – guest459473