How to Integrate Custom Authentication from Your Existing Website Using Flarum API, Flarum-SSO, and JS-Cookie

Sani Joshua - Feb 14 - - Dev Community

Introduction

Flarum is a lightweight and extensible forum software that allows for seamless integration with external authentication systems. If you have an existing website and want to enable single sign-on (SSO) for your users, you can leverage Flarum’s API, SSO extension, and cookies to streamline authentication.

In this guide, we will walk you through the steps to integrate custom authentication into your Flarum forum using your existing website’s credentials.

Prerequisites

Before we begin, ensure you have the following:

  • A Flarum instance installed and running.
  • An existing website with user authentication.
  • The Flarum SSO extension installed.
  • Basic knowledge of handling APIs and cookies in JavaScript.

Step 1: Configure Flarum SSO Extension

To enable authentication via your existing website, install the SSO extension in Flarum by running:

composer require maicol07/flarum-ext-sso

After installation, enable the extension from the Flarum admin panel, with the following configuration

Configuration

  1. Signup URL: URL where the user will be redirected when the Signup button is clicked
  2. Login URL: URL where the user will be redirected when the Login button is clicked
  3. Logout URL: URL where the user will be redirected when the Logout button is clicked

For more information see Documentation

Step 2: Generate an API Key in Flarum

API Keys are the primary way for scripts, tools and integrations to interact with Flarum.

Creation

There is currently no UI to manage API Keys, but they can be created manually in the api_keys table of the database.

The following attributes can be filled:
key: Generate a long unique token (recommended: alpha-numerical, 40 characters) and set it here, this will be the token used in the Authorization header.
user_id: Optional. If set, the key can only be used to act as the given user.

Access Tokens

Access Tokens are short-lived tokens that belong to a specific user.

Those tokens are used behind the scenes for cookie sessions. Their use in stateless API requests has the same effect as a regular session. The user last activity will be updated each time the token is used.

Creation

All users are allowed to create access tokens. To create a token, use the /api/token endpoint with the credentials of your user:

POST /api/token HTTP/1.1

{
    "identification": "Toby",
    "password": "pass7word"
}

HTTP/1.1 200 OK

{
    "token": "YACub2KLfe8mfmHPcUKtt6t2SMJOGPXnZbqhc3nX",
    "userId": "1"
}
Enter fullscreen mode Exit fullscreen mode

See Documentation for more information

Store this key securely as it will be used to authenticate API requests.

Step 3: Implement Login Flow on Your Website

Your existing website should handle authentication and then create a session for the user in Flarum. Use the Flarum API to check if the user exists and create one if necessary.

Example: Logging in via API

export const getFlarumToken = async ({
  identification,
  password,
}: {
  identification: string;
  password: string;
}) => {
  try {
    const flarumUser = {
      identification,
      password,
    };

    const res = await fetch("https://your-forum.com/public/api/token", {
      headers: {
        "Content-Type": "application/json",
      },
      method: "POST",
      body: JSON.stringify(flarumUser),
    });
    return await res.json();
  } catch (err) {
    console.log(err, "something went wrong");
  }
};

Enter fullscreen mode Exit fullscreen mode
export const getOrCreateFlarumUser = async ({
  username,
  email,
  password,
}: TCreateFlarumUser) => {
  try {
    const flarumUserOne = await getFlarumToken({
      identification: config.get<string>("flarum.user"),
      password: config.get<string>("flarum.pass"),
    });

    // Generate a Flarum authentication token
    const flarumUser = await getFlarumToken({
      identification: email,
      password: uid,
    });

    if (flarumUser.token) return flarumUser.token;

    const newUser = {
      data: {
        attributes: {
          username,
          email,
          isEmailConfirmed: true,
          password,
        },
      },
    };
    const newUserResponse = await fetch(
      "https://your-forum.com/public/api/users",
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Token ${flarumUserOne.token}`,
        },
        method: "POST",
        body: JSON.stringify(newUser),
      }
    );
    await newUserResponse.json();
    const newFlarumUser = await getFlarumToken({
      identification: email,
      password: uid,
    });

    return newFlarumUser.token;
  } catch (err) {
    console.log("somehting went wrong");
  }
};

Enter fullscreen mode Exit fullscreen mode
export const getFlarumUserHandler = async (req: Request, res: Response) => {
  const email = req.params.email
  const password =  req.params.password
  const username = req.params.username

  const flarumUserToken = await getOrCreateFlarumUser({
    email,
    password,
    username: `flarum-${generateBase62String(7)}`,
  });

  res.status(statusCodes.success.code).json({
    success: true,
    message: "User fetched successfully.",
    flarumUserToken,
  });    
}
Enter fullscreen mode Exit fullscreen mode

If the user does not exist in Flarum, create an account via the API before issuing the login token.

Step 5: Maintain User Session with Cookies

To persist login across your website and Flarum, use cookies for authentication. Store the Flarum token in a cookie that applies across subdomains.

import Cookies from 'js-cookie';

// Fetch token from your server then set cookie like this
Cookies.set('flarum_remember', token, { 
  domain: '.yourdomain.com', 
  secure: true, 
  sameSite: 'None' 
});
Enter fullscreen mode Exit fullscreen mode

Ensure that your Flarum forum and main website share the same root domain.

Step 6: Logout Implementation

To log out a user from both platforms, clear the authentication cookies.

function logoutUser() {
    Cookies.remove('flarum_remember', { domain: '.yourdomain.com' });
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

By integrating Flarum’s API, SSO extension, and cookies, you can create a seamless authentication experience for users moving between your website and the forum. This approach ensures a unified login process and improves user experience.

. . . . .