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,
// 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' });
});
You can use passport's authenticate function as route middleware in your express application.
app.post('/login',
passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
// Then you can send your json as response.
res.json({message:"Success", username: req.user.username});
});
By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked. If authentication succeeds, the next handler will be invoked and the req.user
property will be set to the authenticated user.
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
Create new route, e.g.: /jsonSend
with res.json
in it and make successRedirect: '/jsonSend'
. That should do it.
Use passport as a middleware.
router.get('/auth/callback', passport.authenticate('facebook'),
function(req, res){
if (req.user) { res.send(req.user); }
else { res.send(401); }
});
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' });
});