2012-10-13 157 views
5

我使用Passport with Express的Passport-Linkedin戰略,允許用戶使用其LinkedIn個人資料登錄。如何設置Passport策略的當前主機策略callbackURL?

我有以下代碼:

passport.use(new LinkedInStrategy({ 
    consumerKey: config.linkedin.LINKEDIN_API_KEY, 
    consumerSecret: config.linkedin.LINKEDIN_SECRET_KEY, 
    callbackURL: "http://localhost:3000/auth/linkedin/callback" 
    }, 
    function(token, tokenSecret, profile, done) { 
    // asynchronous verification, for effect... 
    process.nextTick(function() { 

     // To keep the example simple, the user's LinkedIn profile is returned to 
     // represent the logged-in user. In a typical application, you would want 
     // to associate the LinkedIn account with a user record in your database, 
     // and return that user instead. 
     return done(null, profile); 
    }); 
    } 
)); 

第4行中,我必須手動設置全回調URL。我有一個字符串用於生產,一個用於開發,但我的URL不斷變化,端口也一樣(我使用2臺機器開發)。

如何自動設置URL的第一部分(http://localhost:3000)?是否有expressapp的財產可以讓我這樣做?我需要使用app.use(function(req, res){});嗎?

謝謝!

回答

4

舊的問題,可能y答案只適用於較新的版本。但是,如果有人跑成這樣,像我這樣的,解決方案只是不指定在callbackURL主機名:

passport.use(new LinkedInStrategy({ 
    consumerKey: config.linkedin.LINKEDIN_API_KEY, 
    consumerSecret: config.linkedin.LINKEDIN_SECRET_KEY, 
    callbackURL: "/auth/linkedin/callback" 
    }, 

爲了得到這個爲Heroku的https使用重定向,我們必須告訴系統信任x-forwarded-protocol頭,通過信任代理:

passport.use(new LinkedInStrategy({ 
    consumerKey: config.linkedin.LINKEDIN_API_KEY, 
    consumerSecret: config.linkedin.LINKEDIN_SECRET_KEY, 
    callbackURL: "/auth/linkedin/callback", 
    proxy: true 
    }, 
+2

如果您的應用程序未在根路徑上運行,則不起作用,例如,它在'/ myapp'而不是'/'上運行。 –

0

在我config.js我有一個cfg.site_url,這是一種方式,或者你可以看看req.host

http://expressjs.com/api.html#req.host

// Host: "example.com:3000" 
req.hostname 
// => "example.com" 

不知道如果你有一個REQ對象的上下文。

+0

我開始使用配置字符串,但服務器名稱和端口不斷變化。我在應用程序級別 - 據我所知,獲得req的唯一方法是添加我提到的app.use語句。問題是,它會被每個請求調用。 –

+0

您可以爲您的請求提供中間件。類似於app.get('/ whatever',loadConfigVariable,routes.whatever);'和'app.locals.whatever = config.whatever'內部的loadConfigVariable函數。 – chovy

+0

這就是我試圖避免的 - 另一條路線。我想知道我是否可以在Passport本身中找到這個功能? –

0

最終通過動態構建URL部分和實際端口的回調URL解決了這個問題。因爲它看起來不夠優雅,所以對這個解決方案並不滿意,但是找不到一個在不添加中間件使用調用的情況下獲得實際URL的方法(我確信這比性能更強,而不是簡單的字符串連接)。