PHPackages                             aditya-wiguna/flarum-jwt-sso - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. aditya-wiguna/flarum-jwt-sso

ActiveFlarum-extension[Authentication &amp; Authorization](/categories/authentication)

aditya-wiguna/flarum-jwt-sso
============================

JWT-based SSO extension for Flarum

016PHP

Since Feb 3Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/aditya-wiguna/flarum-jwt-sso)[ Packagist](https://packagist.org/packages/aditya-wiguna/flarum-jwt-sso)[ RSS](/packages/aditya-wiguna-flarum-jwt-sso/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Flarum JWT SSO Extension
========================

[](#flarum-jwt-sso-extension)

A Flarum extension that provides Single Sign-On (SSO) authentication using JWT tokens from your main site.

Features
--------

[](#features)

- JWT-based authentication flow
- Automatic user creation and updates
- Secure token validation
- CSRF protection with state parameters
- Configurable user group assignment
- Optional override of default Flarum login
- Comprehensive error handling

Installation
------------

[](#installation)

1. Install via Composer:

```
composer require aditya-wiguna/flarum-jwt-sso
```

2. Enable the extension:

```
php flarum extension:enable aditya-wiguna-flarum-jwt-sso
```

3. Run migrations:

```
php flarum migrate
```

4. Configure the extension in your Flarum admin panel.

Configuration
-------------

[](#configuration)

### Admin Panel Settings

[](#admin-panel-settings)

1. **Main Site URL**: Base URL of your authentication site
2. **Login URL**: URL where users are redirected for authentication
3. **Logout URL**: URL where users are redirected after logout (optional)
4. **JWT Secret Key**: Secret key used to verify JWT tokens
5. **JWT Issuer**: Expected issuer claim in tokens (optional)
6. **Default Groups**: Comma-separated group IDs for new users
7. **Override Login**: Replace Flarum's default login with SSO only

### Environment Variables (Recommended)

[](#environment-variables-recommended)

```
JWT_SSO_SECRET_KEY=your-secret-key-here
JWT_SSO_MAIN_SITE_URL=https://your-site.com
JWT_SSO_LOGIN_URL=https://your-site.com/auth/flarum
JWT_SSO_LOGOUT_URL=https://your-site.com/logout
JWT_SSO_ISSUER=your-domain.com
```

Authentication Flow
-------------------

[](#authentication-flow)

1. User clicks login in Flarum
2. User is redirected to your main site with state parameter
3. User authenticates on your main site
4. Your main site redirects back to Flarum with JWT token
5. Flarum validates the JWT and creates/updates the user
6. User is logged into Flarum

JWT Token Requirements
----------------------

[](#jwt-token-requirements)

Your main site must return a JWT token with these claims:

### Required Claims

[](#required-claims)

- `sub`: User ID in your system
- `email`: User's email address
- `exp`: Token expiration timestamp

### Optional Claims

[](#optional-claims)

- `iss`: Token issuer (validated if configured)
- `username`: Preferred username
- `name` or `display_name`: User's display name
- `avatar_url`: User's profile picture URL
- `iat`: Token issued at timestamp

### Example JWT Payload

[](#example-jwt-payload)

```
{
  "iss": "your-domain.com",
  "sub": "12345",
  "email": "user@example.com",
  "username": "johndoe",
  "name": "John Doe",
  "avatar_url": "https://example.com/avatar.jpg",
  "iat": 1640995200,
  "exp": 1640998800
}
```

Main Site Integration
---------------------

[](#main-site-integration)

### Redirect URL Structure

[](#redirect-url-structure)

Your login URL should accept these parameters:

- `return_url`: Where to redirect after authentication
- `state`: CSRF protection token

### Response URL Structure

[](#response-url-structure)

After authentication, redirect to the return\_url with:

- `token`: The JWT token
- `state`: The original state parameter
- `error`: Error message (if authentication failed)

### Example Implementation (PHP)

[](#example-implementation-php)

```
// Handle Flarum authentication request
if (isset($_GET['return_url']) && isset($_GET['state'])) {
    $returnUrl = $_GET['return_url'];
    $state = $_GET['state'];

    // Authenticate user (your existing logic)
    if ($user->isAuthenticated()) {
        // Generate JWT token
        $payload = [
            'iss' => 'your-domain.com',
            'sub' => $user->id,
            'email' => $user->email,
            'username' => $user->username,
            'name' => $user->display_name,
            'avatar_url' => $user->avatar_url,
            'iat' => time(),
            'exp' => time() + 3600 // 1 hour
        ];

        $jwt = JWT::encode($payload, $secretKey, 'HS256');

        // Redirect back to Flarum
        $redirectUrl = $returnUrl . '?' . http_build_query([
            'token' => $jwt,
            'state' => $state
        ]);

        header('Location: ' . $redirectUrl);
        exit;
    } else {
        // Authentication failed
        $redirectUrl = $returnUrl . '?' . http_build_query([
            'error' => 'authentication_failed',
            'state' => $state
        ]);

        header('Location: ' . $redirectUrl);
        exit;
    }
}
```

API Endpoints
-------------

[](#api-endpoints)

The extension creates these routes:

- `GET /auth/sso/login` - Initiates SSO login flow
- `GET /auth/sso/callback` - Handles authentication callback
- `POST /auth/sso/logout` - Handles SSO logout

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

1. **"SSO configuration is incomplete"**

    - Ensure Main Site URL and Login URL are configured
    - Check that settings are saved properly
2. **"Invalid token signature"**

    - Verify the JWT secret key matches between systems
    - Ensure both systems use the same algorithm (HS256)
3. **"Token has expired"**

    - Check token expiration time on your main site
    - Ensure system clocks are synchronized
4. **"Invalid state parameter"**

    - Session storage issues
    - CSRF protection triggered
    - Clear browser cache and try again

### Debug Mode

[](#debug-mode)

Enable debug logging by adding this to your main site:

```
// Log JWT payload before encoding
error_log('JWT Payload: ' . json_encode($payload));

// Log generated token
error_log('Generated JWT: ' . substr($jwt, 0, 50) . '...');
```

Security Considerations
-----------------------

[](#security-considerations)

- Always use HTTPS in production
- Use strong, random JWT secret keys
- Implement short token expiration times
- Monitor authentication logs
- See SECURITY.md for detailed security guidelines

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

License
-------

[](#license)

This extension is licensed under the MIT License.

Support
-------

[](#support)

- Create an issue on GitHub for bug reports
- Check existing issues before creating new ones
- Provide detailed information about your setup

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance54

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/26fa895f56fc756676410baca80e97189e4b9f82c6f58c9f3f28d10188b1c1a1?d=identicon)[adityawiguna12](/maintainers/adityawiguna12)

---

Top Contributors

[![aditya-wiguna](https://avatars.githubusercontent.com/u/21081180?v=4)](https://github.com/aditya-wiguna "aditya-wiguna (10 commits)")

### Embed Badge

![Health badge](/badges/aditya-wiguna-flarum-jwt-sso/health.svg)

```
[![Health](https://phpackages.com/badges/aditya-wiguna-flarum-jwt-sso/health.svg)](https://phpackages.com/packages/aditya-wiguna-flarum-jwt-sso)
```

###  Alternatives

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[league/oauth1-client

OAuth 1.0 Client Library

99698.8M106](/packages/league-oauth1-client)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[gesdinet/jwt-refresh-token-bundle

Implements a refresh token system over Json Web Tokens in Symfony

70516.4M35](/packages/gesdinet-jwt-refresh-token-bundle)[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
