Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send json as a response after passport authenticationin node.js

I am trying this git example.

Which works well when I integrated it with my project, but what I want to achieve is to send json as a response to the client/request, instead of successRedirect : '/profile' & failureRedirect : '/signup'.

Is it possible to send a json, or is there some other methods to get the same?

Any help will be appreciated,TU

like image 596
pitu Avatar asked Jun 24 '14 08:06

pitu


People also ask

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.

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.


2 Answers

There is an official Custom Callback documentation:

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

https://github.com/passport/www.passportjs.org/blob/master/views/docs/authenticate.md

like image 110
Arthur Ronconi Avatar answered Sep 21 '22 14:09

Arthur Ronconi


here I modified my code to send json as a response

// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
    successRedirect : '/successjson', // redirect to the secure profile section
    failureRedirect : '/failurejson', // redirect back to the signup page if there is an error
    failureFlash : true // allow flash messages
}));

app.get('/successjson', function(req, res) {
    res.sendfile('public/index.htm');
});

app.get('/failurejson', function(req, res) {
    res.json({ message: 'hello' });
});
like image 39
pitu Avatar answered Sep 22 '22 14:09

pitu