OAuth Providers

This page explains existing OAuth providers and how to setup additional ones.

To search for available Passport strategies use PassportJS Strategies list.

Dependencies

First of all we need to install libraries needed to implement OAuth provider

yarn add passport-facebook

Environment Variables

Register your application within your OAuth provider (facebook as an example)

  • Register your application at Facebook Developers.

  • Set up the callback URL in your Facebook app configuration:

    <BASE_URL>/auth/callback

API

.env
FACEBOOK_APP_ID=your_id
FACEBOOK_APP_SECRET=your_secret
constants.ts
FACEBOOK_APP_ID: process.env.FACEBOOK_APP_ID,
FACEBOOK_APP_SECRET: process.env.FACEBOOK_APP_SECRET,

UI

.env.development
REACT_APP_FACEBOOK_CLIENT_ID=your_id

Data Types

Since we're using TypeScript, it's crucial to define appropriate data types to

Strategy Class

FacebookStrategy extends PassportStrategy from Passport.js and implements the Facebook OAuth login flow.

  • Constructor:

    • Initializes the Facebook strategy with required options such as clientID, clientSecret, and callbackURL.

    • Logs an error if Facebook credentials (FACEBOOK_APP_ID and FACEBOOK_APP_SECRET) are not provided in constants.

  • Options:

    • clientID: Facebook App ID.

    • clientSecret: Facebook App Secret.

    • callbackURL: URL that Facebook redirects to after successful authentication.

    • scope: Scope of permissions; here, it requests access to the user's email.

    • profileFields: Specifies the fields retrieved from the Facebook profile (e.g., emails, name, picture).


validate Method

This method processes the Facebook profile data to create an OAuthPayload object and pass it to the done callback.

  • Parameters:

    • accessToken & refreshToken: Tokens returned by Facebook for accessing user information.

    • profile: Facebook profile object containing user information.

    • done: Callback to complete the validation process.

  • Data Mapping:

    • Maps profile fields to the OAuthPayload fields:

      • email: Primary email of the user.

      • firstName: User's first name.

      • lastName: User's last name.

      • picture: Profile picture URL.

  • Error Handling:

    • If an error occurs, handleError() is invoked, returning a BAD_REQUEST HTTP error with a user-friendly message.

After creating strategy we need to register it within a module

API Usage

Create endpoints in an AuthController to start the Facebook OAuth flow.

OAuth Button

The component renders a Button styled for Facebook sign-in. When clicked, it begins the Facebook login process, handling responses and redirections based on authentication status.

  • State and Hooks:

    • useState for loading: Indicates when the login request is being processed.

    • useAuth, useAuthService, and useNavigate: Contexts and services for handling authentication state and navigation.

    • useEffect and useCallback manage the popup's event listeners and message handling.

  • URL Construction (getCode function):

    • Constructs the Facebook OAuth URL using the client ID and redirect URI.

    • Initiates the OAuth flow by calling openSignInWindow.

  • Popup Handling (openSignInWindow and receiveMessage functions):

    • openSignInWindow creates the popup for Facebook’s OAuth and sets up a message listener.

    • receiveMessage processes the OAuth response:

      • Checks the event origin for security.

      • Parses the code parameter returned by Facebook.

      • Calls the facebookAuth function with the code to retrieve the user’s tokens.

  • Authentication and Navigation Logic:

    • After receiving the tokens, the accessToken, refreshToken, and isTwoFactorEnable are evaluated:

      • If 2FA is enabled, redirects to the 2FA setup route.

      • Otherwise, stores tokens and navigates to the root path.

  • Error Handling:

    • Displays an error notification if there’s an issue during authentication.

    • Switches the active tab to the sign-up screen if necessary.

OAuth Callback

This component should be set as the callbackURL route in your app’s router configuration. After Facebook redirects to this route, the component completes the OAuth handshake by communicating the response back to the original window and closing itself

  • useEffect Hook:

    • When the component mounts, it retrieves the URL parameters (window.location.search), which includes the OAuth code sent by Facebook after the user authorizes the app.

  • Message Posting:

    • It checks if the current window has an opener (the original window that opened the popup).

    • If an opener exists, it sends the URL parameters back to the opener using window.opener.postMessage(params). The original window then handles these parameters (e.g., by extracting the authorization code).

  • Popup Closure:

    • After posting the message, window.close() is called to close the popup, finishing the OAuth flow.

Sequence Diagram

This OAuth flow diagram helps provide a clear visual representation of how authentication works between the UI, API, and OAuth provider.

OAuth flow sequence diagram

Google oAuth2Facebook oAuth2

Last updated