First, install the passport package and plug it in the middle ware pipeline of the express app:
var passport = require('passport'); app.use(passport.initialize()); app.use(passport.session());
Second, you will need to define the routes that handle the oauth flow:
var express = require("express"); var passport = require('passport'); var router = express.Router(); router.get('/google', passport.authenticate('google', { scope: 'email' } )); router.get('/google/callback', passport.authenticate('google', { successRedirect: '/', failureRedirect: '/', failureFlash: "Login failed, please try again." }));
The paths of the routes don't matter, the important part is that when the '/google' url is hit passport will authenticate with whatever strategy is registered. The Google OAuth strategy will initiate an OAuth flow. The second route will act as the end of the OAuth flow (once google redirects back to the application). It is a bit weird that it uses the same 'passport.authenticate' call, but it is the authentication strategy that will be in charge of inspecting the tokens at each step of the flow.
Then, you will need to install the passport-google-oauth package and register it with passport:
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; passport.use(new GoogleStrategy({ clientID: GOOGLE_CLIENT_ID, clientSecret: GOOGLE_CLIENT_SECRET, callbackURL: hostUrl + "/auth/google/callback", passReqToCallback: true }, function(req, accessToken, refreshToken, profile, done) { done(null, { id: profile.id, name: profile.displayName }); } ));
The strategy needs to be configured with the client id and secret and the callback function gives and opportunity to create the user object that will be stored in session between requests. The last thing of course is to go to Google API Console to register the application and get the client id and secret.
Source code is available at bitbucket or you can play with the live test site.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.