login and register in Mern stack through gmail
Login and Register in MERN Stack through Gmail
Logging in and registering through Gmail is a popular feature in web applications. It saves time and provides a hassle-free experience for users. In MERN stack, it can be implemented using OAuth 2.0 protocol to authenticate users.
Prerequisites
- A MERN stack project
- A Google Cloud Platform account
- A Google Cloud Platform project
Steps to Implement
First, create a new project in the Google Cloud Platform console and enable the Google+ API. Then, create a new OAuth client ID and set the authorized redirect URI to your application's callback URL (e.g. http://localhost:3000/auth/google/callback).
Next, install the passport and passport-google-oauth2 packages using npm. These packages provide the necessary functionality for authenticating users using Google OAuth 2.0.
npm install passport passport-google-oauth2
In your MERN stack app, create a new route for handling authentication with Google. This route should use passport.js to authenticate the user using the passport-google-oauth2 strategy.
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth2').Strategy;
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
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 to dashboard.
res.redirect('/dashboard');
});
This code sets up the Google OAuth 2.0 strategy using the client ID, client secret, and callback URL from your Google Cloud Platform project. The '/auth/google' route will redirect the user to Google's login screen, where they will be prompted to grant permission for your app to access their Google account. After successful authentication, the user will be redirected to the '/auth/google/callback' route, where their user data will be stored in your app's database and they will be redirected to the dashboard.
That's it! Your users can now log in and register using their Google account in your MERN stack app.