ALMEFY JWT Authentication: Integration Guide

This document outlines the integration of ALMEFY's JWT (JSON Web Token) authentication within your application. Unlike our traditional workflow relying on SAML 2.0 or OIDC, JWT authentication facilitates a stateless, server-to-server interaction, making it an ideal choice for applications that [ ... ]

How JWT Authentication Works

The process begins with the client application displaying a login interface. When a user successfully authenticates via the ALMEFY API, the API issues a JWT back to your application's backend. This token, which includes the user's unique identifier and a digital signature, is then used to establish and maintain a secure session within your application.

Integration Steps

Follow these steps to integrate ALMEFY into your application, or have a look at this working sample on GitHub.

Using SDKs for Integration (Backend)

While you can work directly with our REST API, we suggest using one of ALMEFY's SDKs. They make the integration smoother and take care of the heavy lifting for you. If you still want to go with the REST API, all the details are on our documentation site.

SDK Options:

  • PHP: Easy to set up with Composer for PHP projects.

    composer require almefy/client
  • Node.js: Use npm to add it to Node.js projects, great for JavaScript environments.

    npm install almefy-client --save
  • .NET: For .NET projects, clone the SDK from GitHub and add it to your solution.

    git clone https://github.com/almefy/almefy-dotnet-client.

Using these SDKs, you get a quicker start and less hassle with your integration.

1. Embedding the ALMEFY Login Widget

Add the ALMEFY login widget to your application's frontend. This widget displays a QR code that users scan to authenticate with the ALMEFY API.

HTML Snippet for Login Widget:

<div data-almefy-auth
     data-almefy-key="YOUR_ALMEFY_KEY"
     data-almefy-auth-url="/your-backend-auth-endpoint"></div>

<script async src="https://cdn.almefy.com/js/almefy-0.9.8.js"
        integrity="sha384-YrIFSeu+BqWh1wivbt+Q90LfEPlPMvlrel3UTRT2FWTc8P1HauLvZNQcoRBzCMpo"
        crossorigin="anonymous"></script>

Replace YOUR_ALMEFY_KEY with your endpoints actual public key and /your-backend-auth-endpoint with the endpoint in your backend designed to handle the JWT.

You will find the public key in the left column of the "Add Endpoint" page, when creating a new JWT endpoint, or on the settings page of an exisiting endpoint.

2. Configuring the Backend Login Controller

After the user authenticates, the ALMEFY API sends the JWT to the specified backend endpoint. Your backend should validate this token, verify the user's identity against your user database, and set up the user's session.

Example of a Backend Controller in PHP:

require_once __DIR__ . '/vendor/autoload.php';

// Provided in the endpoint settings of your ALMEFY Hub.
$client = new \Almefy\Client('YOUR_ALMEFY_KEY', 'YOUR_ALMEFY_SECRET');

function authRequest($request) {
    $jwt = $request->headers->get('X-Almefy-Authorization');
    $token = $client->decodeJwt($jwt);

    //Substitute with your own abstraction layer
    $user = $userRepository->findByEmail($token->getIdentifier());

    if (!$user || !$user->isActive()) {
        return false;  // User not found or inactive
    }

    if (!$client->authenticate($token)) {
        return false;  // Invalid token
    }

    return true;  // Successful authentication
}

In this controller, replace YOUR_ALMEFY_KEY and YOUR_ALMEFY_SECRET with your actual credentials. The $userRepository should be a component of your application responsible for retrieving user data from your database.

3. Enrolling Users (Optional)

The easiest way to add users is through the ALMEFY Hub. But if you want to add users from your app, you can do that too with our SDK.

Adding Users Automatically

Our SDK lets you add users right from your backend. This way, you can send them an email with a QR code to sign in.

We are using an email as the identifier in this example. But you could use any unique string instead.

PHP Example to Add Users:

function addUser($email) {
    global $client;  // Make sure to use your Almefy client

    try {
        // Tell ALMEFY to add the user and send them an email
        $client->enrollIdentity($email, [
            'sendEmail' => true,  // ALMEFY will send the email
            'sendEmailTo' => $email  // User's email
        ]);
    } catch (\Almefy\Exception\TransportException $e) {
        echo 'Couldn't add user: ' . $e->getMessage();
    }
}

This code adds a new user with their email and asks ALMEFY to email them. If an identifier is already registerted, we will create an enrollment for the existing user.

Getting a QR Code for Manual Use

If you want to use the QR code in your own way, like in your app or a custom email, you can get the QR code without ALMEFY sending an email.

PHP Example for QR Code:

function getQRCode($email) {
    global $client;  // Make sure to use your Almefy client

    try {
        // Add the user but don't send an email, just get the QR code
        $enrollmentToken = $client->enrollIdentity($email, [
            'sendEmail' => false  // We'll handle the QR code
        ]);

        // Get the QR code image data
        return $enrollmentToken->getBase64ImageData();
    } catch (\Almefy\Exception\TransportException $e) {
        echo 'Couldn't get QR code: ' . $e->getMessage();
    }
}

This code adds a user and gives you the QR code image data as a base64 string, so you can use it however you like.

Conclusion

This guide provides a concise overview of integrating ALMEFY's JWT authentication into your application. By following the steps outlined above, you can securely authenticate users against the ALMEFY API, ensuring that only authorized individuals can access your application's resources.

Contact Almefy Support: Reach out to us via our contact form for assistance with setup issues. Please provide detailed information about the problem you're facing, and our support team will be happy to assist you.