Monday 13 March 2017

Passport.js stateless/sessionless google auth

I want to write a stateless node api with passport.js for authentication.

I want to create an oauth google api endpoint that returns the api key on success and other details on success.

Google API route

router.get('/',passport.authenticate('google', { scope : ['profile', 'email']}));


router.get('/callback', function(req, res, next) {
    passport.authenticate('google', { session: false, failureRedirect: '/#/login'}, function(err, user, info) {
        console.log('------------------in google callback-----------------');
        if (err) res.status(500).json({status_code: 500, message: "Authentication error", data : err});

        if (!user) {
             res.status(404).json({status_code: 404, message : "User not found/created"});
        }
        var token = 'JWT KEY TO USE AS API TOKEN'; 
        res.status(200).json({status_code: 200, message : "Success", data : {token : token, user:user }});
    })(req, res, next);

});

When i open my api endpoint in browser on successfull authentication the json response is just printed on the screen and i have no way to capture the same in a variable. Calling the same api endpoint via ajax doesn't work.

This is how i recieve the json response

How do i create a google login api endpoint that works without sessions and returns a token?

How can i run this via ajax? Is there any way to call this api end point and recieve the response in a success callback?



via Vinay Naik

No comments:

Post a Comment