Auth ~ Passport Google OAuth - rohit120582sharma/Documentation GitHub Wiki
Passport strategy for authenticating with Google using the OAuth 2.0 API.
This module lets you authenticate using Google in your Node.js applications.
$ npm install passport-google-oauth20
Before using passport-google-oauth20, you must register an application with Google. If you have not already done so, a new project can be created in the Google Developers Console.
Your application will be issued a client ID and client secret, which need to be provided to the strategy. You will also need to configure a redirect URI which matches the route in your application.
The Google authentication strategy authenticates users using a Google account and OAuth 2.0 tokens.
The client ID and secret obtained when creating an application are supplied as options when creating the strategy.
The strategy also requires a verify callback, which receives the access token and optional refresh token, as well as profile which contains the authenticated user's Google profile. The verify callback must call cb providing a user to complete authentication.
var GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback'
},
async (accessToken, refreshToken, profile, cb) => {
try {
const user = await User.findOrCreate({ providerId: profile.id });
return cb(null, user);
} catch(err) {
return cb(err);
}
}
)
);
Use passport.authenticate(), specifying the 'google' strategy, to authenticate requests.
app.get(
'/auth/google',
passport.authenticate('google', { scope: ['profile'] })
);
app.get(
'/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
}
);