This is an Express 4 application using Google for authentication via OAuth2.
Based on the OAuth2 example in Jared Hanson’s passport-google-oauth, this Express 4 application uses Passport and the Passport Google OAuth strategy to enable users to authenticate with their Google accounts.
The client id and client secret needed to authenticate with Google can be set up from the Google Developer's Console.
git clone https://github.com/barberboy/passport-google-oauth2-example myapp
cd myapp && npm install
- Create a project and OAuth 2.0 client ID at https://console.developers.google.com
- Add clientID, clientSecret, and callbackURL to config/auth.json
The Google OAuth 2.0 authentication strategy authenticates users using a Google
account and OAuth 2.0 tokens. The strategy requires a verify
callback, which
accepts these credentials and calls done
providing a user, as well as
options
specifying a client ID, client secret, and callback URL.
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "http://127.0.0.1:3000/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
Use passport.authenticate()
, specifying the 'google'
strategy, to
authenticate requests. Authentication with Google requires an extra scope
parameter. For information, see the
documentation.
app.get('/auth/google',
passport.authenticate('google', { scope: ['email profile'] }));
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Authenticated successfully
res.redirect('/');
});