Skip to content

Rublon/rublon-sdk-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rublon PHP SDK

Table of Contents

  1. Overview
  2. Use Cases
  3. Supported Authentication Methods
  4. Before You Start
  5. Configuration
  6. Laravel Configuration
  7. Troubleshooting

Overview

The Rublon PHP SDK library is a client-side implementation of the Rublon API written in PHP. The library includes methods for embedding the Rublon API’s GUI in an HTML-based environment. The Rublon PHP SDK forms a convenient PHP coding language facade for Rublon API’s REST interface.

Use Cases

Rublon adds an extra layer of security by prompting the user to authenticate using an extra authentication method such as Mobile Push. Even if a malicious actor compromises the user's password, the hacker would not be able to log in to the user's account because the second secure factor will thwart them.

Rublon can add an extra layer of security in the following two use cases:

  1. When a user signs in to a system (after the user enters the correct password)
  2. When a user undergoes a security-sensitive transaction (such as changing the password or conducting a money transfer)

When a user signs in to a system, the second authentication factor should be initiated only after:

  • the user has successfully completed the first authentication factor (e.g., entered the correct password)
  • the user's unique username and email address have been gathered

Supported Authentication Methods

  • Mobile Push - Approve the authentication request by tapping a push notification displayed on the Rublon Authenticator mobile app.
  • Mobile Passcodes (TOTP) - Enter the TOTP code (Time-Based One Time Password) using the Rublon Authenticator mobile app or a third-party authenticator app like Google Authenticator or Microsoft Authenticator.
  • SMS Passcodes - Enter the verification code from the SMS sent to your mobile phone number.
  • QR Codes - Scan a QR code using the Rublon Authenticator mobile app.
  • Email Links - Click the verification link sent to your email address.
  • WebAuthn/U2F Security Keys - Insert the security key into the USB port of your computer and touch it.
  • YubiKey OTP - Insert the YubiKey and tap it to automatically enter the OTP into the text field.

Before You Start

Before you start implementing the Rublon PHP SDK library into your code, you must create an application in the Rublon Admin Console. We also recommend that you install the Rublon Authenticator mobile app for Mobile Push, Mobile Passcode, and QR Code authentication methods.

Create an Application in the Rublon Admin Console

  1. Sign up for the Rublon Admin Console. Here’s how.
  2. In the Rublon Admin Console, go to the Applications tab and click Add Application.
  3. Enter a name for your application and then set the type to Custom integration using PHP SDK.
  4. Click Save to add the new PHP SDK application in the Rublon Admin Console.
  5. Copy and save the values of System Token and Secret Key. You are going to need these values later.

Optional: Install Rublon Authenticator

For increased security of Multi-Factor Authentication (MFA), end-users are recommended to install the Rublon Authenticator mobile app.

Download the Rublon Authenticator for:

After installing the mobile app, users can authenticate using the following authentication methods:

In some cases, users may not want to install any additional apps on their phones. Also, some users own older phones that do not support modern mobile applications. These users can authenticate using one of the following authentication methods instead:

Configuration

Follow the steps below to configure Rublon PHP SDK.

INFO: Initial Assumptions

Let’s assume there is a superglobal session associative array $_SESSION. It has access to an object that stores user data of the currently logged-in user.

The $_SESSION array will be used in PHP code examples later in this document.

INFO: Modifying the Library

The Rublon class implements a few public methods, which, when needed, can be overridden using class inheritance.

We strongly discourage you from modifying any part of the library, as it usually leads to difficulties during library updates. If you need to change the flow or internal structure of the Rublon or RublonCallback classes, do not hesitate to subclass them according to your needs.

Initialize the Library

To initialize the Rublon PHP SDK library, you need to instantiate a Rublon class object. Its constructor takes three arguments.

`Rublon` class constructor arguments
Name Type Description
$systemToken string The System Token value you copied from the Rublon Admin Console.
$secretKey string The Secret Key value you copied from the Rublon Admin Console.
$apiServer string Rublon API Server URI

Default: https://core.rublon.net

Example PHP Code

  require_once "libs/Rublon/Rublon.php";

  $rublon = new Rublon(
     "D166A6E9996A40F0A88252432FA5E490",
     "913eda929c96cf52141b39f5717e25",
     "https://core.rublon.net"
  );

Perform Authentication

The Rublon::auth() method uses the username to check the user's protection status and returns a URL address the user should be redirected to in their web browser.

Rublon::auth() method arguments
Name Type Description
$callbackUrl string The integrated system's callback URL.

Rublon will redirect the user to this URL after successful authentication.

$username string The user's username, which allows the user to sign in
$userEmail string The user's email address, which allows to check the user's protection status and match the user to a Rublon account
$params array Additional transaction parameters (optional)
$isPasswordless boolean Whether the sign-in attempt is passwordless (optional and false by default)

Example PHP Code

    /**
     * An example method used to log the user in (integrated system's method)
     *
     * @param string $login
     * @param string $password
     */
    function login($login, $password) {
        if (loginPreListener()) {
            if ($user = authenticate($login, $password)) {
                // The user has been authenticated.
                $_SESSION["user"] = $user;
                loginPostListener();
            }
        }
    }

    /**
     * Listener (hook) invoked after a successful first factor user authentication,
     * implemented for Rublon integration purposes.
     */
    function loginPostListener() {
        // Make sure that the user is not logged-in
        unset($_SESSION['user']);

        $rublon = new Rublon(
            "D166A6E9996A40F0A88252432FA5E490",
            "913eda929c96cf52141b39f5717e25",
            "https://core.rublon.net"
        );

        try { // Initiate a Rublon authentication transaction
            $authUrl = $rublon->auth(
                $callbackUrl = "http://example.com?rublon=callback",
                $_SESSION["user"]["login"], // Username
                $_SESSION["user"]["email"] // User email
            );

            if (!empty($authUrl)) { // User protection is active
                // Redirect the user's web browser to Rublon servers to verify the protection:
                header('Location: ' . $authUrl);
            } else {
                // User is not protected by Rublon, so bypass the second factor.
                header('Location: index.php');
            }
        } catch (UserDeniedException $e) {
            // Access Denied
            header('Location: ./');
        } catch (UserBypassedException $e) {
            // User bypassed
            header('Location: ./');
        } catch (RublonException $e) {
            // An error occurred
            die($e->getMessage());
        }
    }

Note: Make sure that your code checks that the user is not signed in. The user should be signed in only after successful Rublon authentication.

Verify Configuration

The Rublon::checkApplication() method verifies the validity of the configuration. Your application should call this method every time you change or save the configuration. A configuration change can be, for example, changing the systemToken or secretKey.

Rublon::checkApplication() method arguments
Name Type Description
appVerstringThe version of the current application.
paramsarrayOptional.

Additional application parameters.

Rublon::checkApplication() may throw one of the following exceptions:

  • ApplicationNotFoundException - Invalid System Token
  • InvalidSignatureException - Invalid Secret Key
  • UnsupportedVersionException - Incorrect version of the application

Finalize Authentication

After successful authentication, Rublon redirects the user to the callback URL. The callback flow continues and finalizes the authentication process.

Input Params

The callback URL will receive input arguments in the URL address itself (query string).

Callback URL arguments
Name Type Description
rublonState string Authentication result: ok.
rublonToken string Access token (60 alphanumeric characters, upper- and lowercase), which allows to verify the authentication using a background Rublon API connection

Note: If the callback URL has been set to, e.g., http://example.com/auth, the params will be appended to the URL address:

http://example.com/auth?rublonState=ok&rublonToken=Kmad4hAS...

Note: If you want to construct the callback URL differently (e.g., by using mod_rewrite), you can set the callback URL's template using the meta-tags: %rublonToken% and %rublonState%, like so:

http://example.com/auth/%rublonState%/%rublonToken%

Handle Authentication Result

After the callback is invoked, you need to instantiate a RublonCallback class object for proper finalization of the authentication process.

RublonCallback class constructor method arguments
Name Type Description
$rublon Rublon An instance of the Rublon class

Next, call the RublonCallback::call() method. It takes two arguments:

RublonCallback::call() method arguments
Name Type Description
$successHandler callable The name of the function/method, or an anonymous function/closure, to be invoked on successful authentication
$cancelHandler callable The name of the function/method, or an anonymous function/closure, to be invoked when the callback is canceled
Arguments of the $successHandler function, passed to the RublonCallback::call() method
Name Type Description
$username string The user's unique username in the integrated system, that was passed as an argument to the Rublon::auth() method
$callback RublonCallback An instance of the RublonCallback class
Arguments of the $cancelHandler function, passed to the RublonCallback::call() method
Name Type Description
$callback RublonCallback An instance of the RublonCallback class

Example PHP Code

An example portraying how to use the RublonCallback class in the callback:

  $rublon = new Rublon(
     "D166A6E9996A40F0A88252432FA5E490",
     "913eda929c96cf52141b39f5717e25",
     "https://code.rublon.net"
  );
  
  try {
     $callback = new RublonCallback($rublon);
     $callback->call(
        $successHandler = function($username, RublonCallback $callback) {
           // The user is finally logged in
           $_SESSION["user"] = $username;
        },
        $cancelHandler = function(RublonCallback $callback) {
           // Cancel the authentication process
           header("Location: ./login");
           exit;
        }
     );
     
     // The authentication process was successful, redirect to the main page:
     header("Location: ./");
     exit;
  } catch (RublonException $e) {
     // Please handle this error in the better way
     die($e->getMessage());
  }

Laravel Configuration

This Laravel configuration example uses the Breeze starting kit.

  1. After you create the application and install Breeze, you need to add Rublon PHP SDK:

    composer require Rublon/rublon-sdk-php

  2. Add those to .env:

    RUBLON_TOKEN="your rublon token"

    RUBLON_KEY="your rublon key"

    RUBLON_URL="https://core.rublon.net"

  3. Create new route for Rublon callback in routes/auth.php:

    Route::get('rublon-callback', [AuthenticatedSessionController::class, 'rublonCallback'])->name('rublon-callback');

  4. Modify the store method in the controller:

    Http/Controllers/Auth/AuthenticatedSessionController.php

      public function store(LoginRequest $request)
      {
         $request->authenticate();
    
         $rublon = new Rublon(
            env('RUBLON_TOKEN'),
            env('RUBLON_KEY'),
            env('RUBLON_URL'),
         );
    
         try { // Initiate a Rublon authentication transaction
            $url = $rublon->auth(
               $callbackUrl = url('/rublon-callback'),
               Auth::user()->email, // User email used as username
               Auth::user()->email  // User email
            );
    
            if (!empty($url)) {
               Auth::logout();
               return redirect()->away($url);
            } else {
               // User is not protected by Rublon, so bypass the second factor.
               $request->session()->regenerate();
               return redirect()->to('dashboard');
            }
         } catch (UserBypassedException $e) {
            return redirect()->to('login');
         } catch (RublonException $e) {
            // An error occurred
            die($e->getMessage());
         }
    
         return redirect()->intended(RouteServiceProvider::HOME);
      }
    
  5. Add a new method for Rublon callback:

      public function rublonCallback(Request $request)
      {
         $rublon = new Rublon(
            env('RUBLON_TOKEN'),
            env('RUBLON_KEY'),
            env('RUBLON_URL'),
         );
    
         try {
            $callback = new RublonCallback($rublon);
            $request->session()->regenerate();
            $callback->call(
               $successHandler = function($username, RublonCallback $callback) {
                  $user = User::where('email', $username)->firstOrFail();
                  Auth::login($user);
                  if (Auth::check()) {
                     return redirect()->to('dashboard');
                  } else {
                     return redirect()->to('login');
                  }
               },
               $cancelHandler = function(RublonCallback $callback) {
                  return redirect()->to('login');
               }
            );
    
            return redirect()->to('dashboard');
         } catch (Rublon Exception $e) {
            die($e->getMessage());
         }
    
         return redirect()->to('dashboard');
      }
    

Troubleshooting

If you encounter any issues with your Rublon integration, please contact Rublon Support.