I'm using the Passport-Linkedin strategy for Passport with Express, to allow users to log in with their LinkedIn profile.
I have the following code:
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);
});
}
));
On line 4, I have to set the full callback URL manually. I had one string for production and one for development, but my URLs keep changing, and so do the ports (I use 2 machines to develop).
How can I set the first portion of the URL (http://localhost:3000
) automatically? Is there a property of express
or app
that would allow me to do that? Do I need to resort to an app.use(function(req, res){});
?
Thanks!
Old question, possibly y answer only valid for newer versions. However if someone runs into this, like me, solution is just to not specify a hostname in the callbackURL
:
passport.use(new LinkedInStrategy({
consumerKey: config.linkedin.LINKEDIN_API_KEY,
consumerSecret: config.linkedin.LINKEDIN_SECRET_KEY,
callbackURL: "/auth/linkedin/callback"
},
To get this to work for heroku https redirect, we have to tell the system to trust the x-forwarded-protocol
headers, by trusting the proxy:
passport.use(new LinkedInStrategy({
consumerKey: config.linkedin.LINKEDIN_API_KEY,
consumerSecret: config.linkedin.LINKEDIN_SECRET_KEY,
callbackURL: "/auth/linkedin/callback",
proxy: true
},
In my config.js I have a cfg.site_url, that's one way, or you could look at req.host
http://expressjs.com/api.html#req.host
// Host: "example.com:3000"
req.hostname
// => "example.com"
Not sure if you have a req object in your context there.
Eventually solved this by dynamically building the callback URL from pieces of URL and the actual port. Not happy with this solution as it looks non-elegant, but could not find a way to get the actual URL without adding a middleware use call (which I'm sure impacts performance more than a simple string concatenation).