Mastering Social Authentication with Google in ExpressWebJs

Mastering Social Authentication with Google in ExpressWebJs

Introduction:

Authentication is a crucial aspect of web development, and ExpressWebJs makes it even more powerful by seamlessly integrating social authentication with OAuth providers like Facebook, Twitter, LinkedIn, Microsoft, and, of course, Google. In this guide, we'll walk you through the process of setting up and implementing social authentication using Google as the OAuth provider in ExpressWebJs.

Configuration:

To kickstart social authentication, head over to the Socials.ts file located at Config/Socials.ts. This is where you'll configure your preferred driver, and ExpressWebJs provides support for various social connections, including Google. Here's a snippet to get you started:

social_connections: ["google"], // Add more drivers if needed

connections: {
  google: {
    driver: "google",
    clientID: env("GOOGLE_CLIENT_ID"),
    clientSecret: env("GOOGLE_CLIENT_SECRET"),
    callbackURL: "http://localhost:5000/api/auth/google/callback",
  },
  // Add configurations for other social connections as needed
},

Make sure to securely store your client ID and client secret within your environment variables.

Social service Provider:

Before we proceed, let's install express-session.

yarn add express-session

once it is installed head over to AppServiceProvider to configure express-session and register SocialServiceProvider as a Singleton

import { ServiceProvider } from "Elucidate/Support/ServiceProvider";
import session from "express-session";
import SocialServiceProvider from "Elucidate/Social/SocialServiceProvider";

export class AppServiceProvider extends ServiceProvider {
  /**
   * Register any application services.
   * @return void
   */
  public register() {
    this.singleton(SocialServiceProvider);
  }

  /**
   * Bootstrap any application services.
   * @return void
   */
  public async boot() {
    const app = this.use("Application");
    await app.use(
      session({
        secret: "your_secret_key", // Replace with a secret key for session encryption
        resave: false,
        saveUninitialized: true,
      })
    );
  }

  /**
   * Load any service after application boot stage
   * @return void
   */
  public async booted() {
    //
  }
}

Drivers:

ExpressWebJs supports multiple drivers for social authentication, including Facebook, Twitter, Google, LinkedIn, and Microsoft. Each driver requires specific configuration parameters like client ID, client secret, and callback URL.

Authenticate Requests:

Once configured, you can access the Social object in your route handlers using the Social.use() method. For instance, to redirect a user to Google's OAuth provider website, you can use the following code:

import Route from "Elucidate/Route/manager";
import Social from "Elucidate/Social";

Route.get("/auth/google", Social.use("google", { scope: ["email", "profile"] }));

Handling the Callback Request:

After the user approves or rejects the login request, the OAuth provider will redirect them back to the specified callback URL. You can then access the user with the Social.authenticate() method. Here's an example:

import Route from "Elucidate/Route/manager";
import Social from "Elucidate/Social";

Route.get("/google/callback", function (req, res) {
  Social.authenticate("google", req, res)
    .then((google: { user: object }) => {
      let user = google.profile;
      // Process user data
      console.log(user);
    })
    .catch((err: any) => {
      // Handle errors
      console.log(err);
    });

  res.redirect("/api/");
});

Alternatively, you can handle the callback in a controller for cleaner code organization:

import Route from "Elucidate/Route/manager";
import Social from "Elucidate/Social";

// Handle callback in GoogleController
Route.get("/google/callback", "GoogleController@googleCallback");

GoogleController:

Here's an example of how you can structure your GoogleController to handle the Google callback:

import Social from "Elucidate/Social";
import { Request, Response } from "Config/Http";

export class GoogleController {
  public async googleCallback(req: Request, res: Response) => {
     const google: { user: object } = (await Social.authenticate("google", req, res)) as { user: object };
    console.log(google);

    res.redirect("/api/");
  };
}

By following these steps, you can effortlessly implement social authentication with Google in ExpressWebJs, enhancing your web application's security and user experience.

Hope this article was helpful, Kindly:

Star to support ExpressWebJs on GitHub

And also, follow on Twitter @ ExpressWebJs