passport-google-oauth20

repository·master·Indexed 21 days ago

https://github.com/jaredhanson/passport-google-oauth2

A Passport.js strategy for Node.js applications to authenticate users via Google using the OAuth 2.0 protocol. Includes configuration for GoogleStrategy, implementation of login and callback routes, and error handling for GooglePlusAPIError and UserInfoError.

Tokens
1.5K
Snippets
5
Records
6
Agent score
74%

What's inside passport-google-oauth20

  1. Define Google authentication routes

    master

    You need to implement two routes to handle the OAuth 2.0 flow:

    1. The Login Route: Redirects the user to Google to begin the authentication process.
    2. The Callback Route: Processes the response from Google after the user authenticates and redirects them back to your application.

    When defining the callback route, you can pass options to passport.authenticate such as failureRedirect and failureMessage to handle unsuccessful login attempts.

    // 1. The route that initiates the login
    app.get('/login/google', passport.authenticate('google'));
    
    // 2. The callback route that Google redirects to
    app.get('/oauth2/redirect/google',
      passport.authenticate('google', { failureRedirect: '/login', failureMessage: true }),
      function(req, res) {
        // Successful authentication, redirect home
        res.redirect('/');
      });
  2. Install passport-google-oauth20

    master

    Install the strategy via npm to use Google OAuth 2.0 authentication in your Node.js application.

    For TypeScript users, you should also install the corresponding type declarations.

    $ npm install passport-google-oauth20
    
    # For TypeScript type declarations
    $ npm install @types/passport-google-oauth20
  3. Configure the GoogleStrategy

    master

    To use the strategy, you must first register your application with Google to obtain a clientID and clientSecret.

    Initialize the strategy using new GoogleStrategy(options, verify).

    Configuration Options

    • clientID: Your Google application client ID.
    • clientSecret: Your Google application client secret.
    • callbackURL: The OAuth 2.0 redirect endpoint where Google will send the user after authentication.
    • scope: An array of strings defining the permissions requested (e.g., ['profile']).
    • state: Set to true to enable state parameter support for CSRF protection.

    The Verify Function

    The verify function is called after successful authentication. It receives the following arguments:

    • accessToken: Used for making API requests on behalf of the user.
    • refreshToken: Used to obtain new access tokens.
    • profile: A normalized profile object containing user information from Google (e.g., profile.id, profile.displayName).
    • cb: A callback function used to signal completion. It accepts cb(err, user) or cb(err, false) if authentication fails.
    var GoogleStrategy = require('passport-google-oauth20');
    
    passport.use(new GoogleStrategy({
        clientID: process.env['GOOGLE_CLIENT_ID'],
        clientSecret: process.env['GOOGLE_CLIENT_SECRET'],
        callbackURL: 'https://www.example.com/oauth2/redirect/google',
        scope: [ 'profile' ],
        state: true
      },
      function verify(accessToken, refreshToken, profile, cb) {
        // Logic to find or create a user in your database
        // Example: db.get('SELECT * FROM users WHERE google_id = ?', [profile.id], ...)
        // On success: return cb(null, user);
        // On failure: return cb(null, false);
      }
    ));
  4. Use the Google OAuth 2.0 Strategy

    master

    The passport-google-oauth20 package exports the Strategy class, which is used to integrate Google OAuth 2.0 authentication into a Passport.js application. You can require the package directly to get the Strategy constructor, or access it via the .Strategy property.

    const GoogleStrategy = require('passport-google-oauth20').Strategy;
    
    // Or
    const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
  5. Handle GooglePlusAPIError during authentication

    master

    When interacting with the Google+ API via this strategy, errors returned by the API are wrapped in a GooglePlusAPIError. You can catch this error to inspect the specific error message and the numeric code returned by Google to implement custom error handling or troubleshooting logic.

    try {
      // ... authentication logic that might trigger a Google+ API call
    } catch (err) {
      if (err.name === 'GooglePlusAPIError') {
        console.error('Google+ API Error:', err.message);
        console.error('Error Code:', err.code);
      } else {
        throw err;
      }
    }