Home > Web Front-end > JS Tutorial > body text

Unlocking the Power of Google OAuth with Passport.js: A Step-by-Step Guide

WBOY
Release: 2024-08-12 18:36:35
Original
980 people have browsed it

Hey there, fellow developers! ? Are you ready to level up your authentication game? Today, we're diving into the world of Google OAuth 2.0 and how to implement it using Passport.js. Trust me, your users will thank you for this smooth and secure login experience!

Unlocking the Power of Google OAuth  with Passport.js: A Step-by-Step Guide

Why Google OAuth 2.0? ?

Before we jump in, let's talk about why Google OAuth 2.0 is such a big deal:

1. User-Friendly: No more "forgot password" headaches!
2. Fort Knox Security: Leverage Google's top-notch security protocols.
3. Trust Booster: Users feel safer using their Google accounts.

Sounds good, right? Let's get started!

Step 1: Gear Up! ?️

First things first, let's install our tools. Fire up your terminal and run:

npm install passport passport-google-oauth2 express-session
Copy after login

These packages are your new best friends for implementing Google OAuth 2.0.

Step 2: Google Developer Console Adventure ?️

Time to set up your project in the Google Developer Console. Here's your treasure map:

1. Head to the Google Developer Console.
2. Create a new project (give it a cool name!).
3. Navigate to "APIs & Services > Credentials".
4. Click "Create Credentials" and choose "OAuth 2.0 Client IDs".
5. Set up your consent screen (don't forget to smile for the icon!).
6. Configure your OAuth 2.0 Client ID (Web application type).
7. Add your redirect URI (e.g., http://localhost:3000/auth/google/callback).

Pro Tip: Keep your Client ID and Client Secret safe. They're like the keys to your OAuth kingdom!

Step 3: Passport Configuration Magic ✨

Now, let's sprinkle some Passport.js magic into our app:

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    // Your user-saving logic goes here!
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));

// Don't forget to serialize and deserialize your users!
passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  });
});
Copy after login

Step 4: Route to Success ?️

Let's set up our authentication highways:

const express = require('express');
const passport = require('passport');
const app = express();

app.use(passport.initialize());
app.use(passport.session());

// The gateway to Google OAuth
app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] })
);

// Welcome back! Handle the callback
app.get('/auth/google/callback',
  passport.authenticate('google', { 
    successRedirect: '/auth/google/success', 
    failureRedirect: '/auth/google/failure' 
  })
);

// Success and failure destinations
app.get('/auth/google/success', (req, res) => { 
  res.send('Welcome aboard! ?'); 
});

app.get('/auth/google/failure', (req, res) => { 
  res.send('Oops! Something went wrong. ?'); 
});

app.listen(3000, () => {
  console.log('Server is up and running! ?');
});
Copy after login

Step 5: Launch Time! ?

Set up your environment variables (GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET), and you're ready for liftoff!

node app.js
Copy after login

Navigate to http://localhost:3000/auth/google, and watch the magic happen!

Wrapping Up ?

And there you have it, folks! You've just implemented Google OAuth 2.0 with Passport.js. Your users can now log in with their Google accounts, enjoying a seamless and secure experience.

Remember, this is just the beginning. In a production app, you'd want to add more features like:

  • Proper error handling
  • User data storage in a database
  • Additional authentication options

Have you tried implementing OAuth in your projects? What challenges did you face? Drop your thoughts in the comments below – I'd love to hear about your adventures in the land of authentication!

Happy coding, and may your logins always be smooth! ??‍??‍?

The above is the detailed content of Unlocking the Power of Google OAuth with Passport.js: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template