Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return to the current hash location using Passport.js?

I'm using Passport.js to authenticate with Google via OAuth (I'm using the passport-google-oauth strategy). It works fine, but I'm currently redirecting the user to "/", and I'd like to send them to "/" plus the current hash tag. I can send the hash value in a query string parameter, but I can't seem to set that value to the callbackURL property of the object that I'm passing to authenticate.

Can someone provide an example or explanation as to the correct way to do this? I'm not beholden to using the query string, it just seemed the most straight-forward route, but I'm open to using a session variable or something else, if that would be easier or better practice.

Thank you.

like image 965
Mike Pateras Avatar asked Sep 06 '12 05:09

Mike Pateras


People also ask

What does Passport authenticate () do?

In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.

Should I use Passport js for authentication?

Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.

How does Passport js handle authorization?

Authorization is performed by calling passport. authorize() . If authorization is granted, the result provided by the strategy's verify callback will be assigned to req.account . The existing login session and req.


1 Answers

You can achieve this effect by storing the return url in the session.

// server
var app, express;

express = require('express');

app = express();

app.configure(function() {
  app.use(express.cookieSession({secret: 'shh'}));
});

app.get('/auth/twitter', function(req, res, next) {
  // to return to '/#/returnHash', request this url:
  // http://example.com/auth/twitter?return_url=%2F%23%2FreturnHash

  // on the client you can get the hash value like this:
  // encodeURIComponent("/"+window.location.hash)
  req.session.return_url = req.query.return_url;
  next();
}, passport.authenticate('twitter'));

app.get('/auth/twitter/callback', passport.authenticate('twitter', {
  failureRedirect: '/login'
}), function(req, res) {
  var url = req.session.return_url;
  delete req.session.return_url;

  // redirects to /#/returnHash
  res.redirect(url);
});
like image 80
nrw Avatar answered Nov 10 '22 01:11

nrw