PHPackages                             insol-dev/central-authentication-server - 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. insol-dev/central-authentication-server

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

insol-dev/central-authentication-server
=======================================

Laravel client package for CAS (Central Authentication Server) — SSO integration with JWT tokens, HMAC signature validation, and role-based access control.

v1.0.2(1mo ago)08MITPHPPHP ^7.3|^8.0

Since Apr 7Pushed 1mo agoCompare

[ Source](https://github.com/insol-dev/central-authentication-server)[ Packagist](https://packagist.org/packages/insol-dev/central-authentication-server)[ Docs](https://github.com/insol-dev/central-authentication-server)[ RSS](/packages/insol-dev-central-authentication-server/feed)WikiDiscussions main Synced 4w ago

READMEChangelogDependencies (5)Versions (3)Used By (0)

Laravel CAS Client Package
==========================

[](#laravel-cas-client-package)

A Laravel package for seamless integration with Central Authentication Service (CAS) servers. This package provides secure single sign-on authentication with JWT tokens, signature validation, and role-based access control.

Features
--------

[](#features)

- 🔐 **Secure SSO Authentication** - JWT token-based authentication
- 🛡️ **Signature Validation** - HMAC SHA-256 request signing
- 👥 **Role-Based Access Control** - Middleware for role protection
- 🔧 **Easy Configuration** - Environment-based setup
- 📝 **Comprehensive Logging** - Authentication event tracking
- ⚡ **Performance Optimized** - Token caching and validation
- 🎯 **Laravel Integration** - Native Laravel guards and middleware

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

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require insol-dev/central-authentication-server
```

### 2. Publish Configuration

[](#2-publish-configuration)

```
php artisan vendor:publish --tag=cas-client-config
```

### 3. Configure Environment Variables

[](#3-configure-environment-variables)

Add the following to your `.env` file:

```
# CAS Server Configuration
CAS_SERVER_URL=http://localhost:5000
CAS_CLIENT_ID=your_client_id
CAS_CLIENT_USERNAME=your_client_username
CAS_CLIENT_PASSWORD=your_client_password

# Security Settings
CAS_SIGNATURE_SECRET=your-256-bit-signature-secret
CAS_ENABLE_SIGNATURE_VALIDATION=true

# Callback Configuration
CAS_CALLBACK_URL=http://yourapp.com/cas/callback
```

Quick Start
-----------

[](#quick-start)

### 1. Protect Routes with Middleware

[](#1-protect-routes-with-middleware)

```
// In routes/web.php
use CasSystem\LaravelClient\Middleware\CasAuthentication;
use CasSystem\LaravelClient\Middleware\CasRole;

Route::middleware([CasAuthentication::class])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/profile', [ProfileController::class, 'show']);
});

// Protect with specific roles
Route::middleware([CasAuthentication::class, CasRole::class . ':admin,manager'])->group(function () {
    Route::get('/admin', [AdminController::class, 'index']);
});
```

### 2. Manual Authentication

[](#2-manual-authentication)

```
use CasSystem\LaravelClient\Facades\CasClient;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $returnUrl = $request->query('return_url', route('dashboard'));
        $loginUrl = CasClient::getLoginUrl($returnUrl);
        return redirect($loginUrl);
    }

    public function callback(Request $request)
    {
        $token = $request->query('token');

        if (!$token) {
            return redirect()->route('login')->with('error', 'No authentication token provided');
        }

        $user = CasClient::validateToken($token);

        if ($user) {
            // Store user data in session
            session([
                'cas_user' => $user,
                'cas_token' => $token,
                'authenticated' => true
            ]);

            return redirect()->route('dashboard')->with('success', 'Login successful');
        }

        return redirect()->route('login')->with('error', 'Authentication failed');
    }

    public function logout(Request $request)
    {
        $token = session('cas_token');

        // Logout from CAS server
        CasClient::logout($token);

        // Clear local session
        session()->forget(['cas_user', 'cas_token', 'authenticated']);
        session()->invalidate();
        session()->regenerateToken();

        return redirect('/')->with('success', 'Logged out successfully');
    }
}
```

### 3. Access User Data

[](#3-access-user-data)

```
// In your controllers
public function dashboard(Request $request)
{
    $user = session('cas_user');
    $username = $user['username'];
    $email = $user['email'];
    $roles = $user['roles'] ?? [];

    return view('dashboard', compact('user', 'username', 'email', 'roles'));
}

// Check user roles
use CasSystem\LaravelClient\Facades\CasClient;

if (CasClient::userHasRole($user, 'admin')) {
    // User has admin role
}

if (CasClient::userHasAnyRole($user, ['admin', 'manager'])) {
    // User has admin OR manager role
}

if (CasClient::userHasAllRoles($user, ['user', 'verified'])) {
    // User has BOTH user AND verified roles
}
```

### 4. Blade Templates

[](#4-blade-templates)

```
{{-- In your Blade templates --}}
@if(session('authenticated'))

        Welcome, {{ session('cas_user.name') }}
        Email: {{ session('cas_user.email') }}
        Roles: {{ implode(', ', session('cas_user.roles', [])) }}

        @csrf
        Logout

@else
    Login with CAS
@endif
```

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

[](#configuration)

### Environment Variables

[](#environment-variables)

```
# Required Settings
CAS_SERVER_URL=http://localhost:5000              # CAS server URL
CAS_CLIENT_ID=your_client_id                      # Your registered client ID
CAS_CLIENT_USERNAME=your_client_username          # Client authentication username
CAS_CLIENT_PASSWORD=your_client_password          # Client authentication password

# Security Settings
CAS_SIGNATURE_SECRET=your-256-bit-secret          # HMAC signature secret
CAS_ENABLE_SIGNATURE_VALIDATION=true              # Enable request signing

# Callback Configuration
CAS_CALLBACK_URL=http://yourapp.com/cas/callback  # Where CAS redirects after login

# Optional Settings
CAS_TIMEOUT=30                                     # HTTP request timeout
CAS_VERIFY_SSL=true                               # Verify SSL certificates
CAS_CACHE_ENABLED=true                            # Enable user data caching
CAS_CACHE_TTL=3600                                # Cache time-to-live (seconds)
CAS_LOGGING_ENABLED=true                          # Enable authentication logging
```

### Advanced Configuration

[](#advanced-configuration)

Edit `config/cas-client.php` for advanced options:

```
return [
    // User management
    'user' => [
        'create_local_users' => true,
        'model' => App\Models\User::class,
        'field_mapping' => [
            'username' => 'username',
            'email' => 'email',
            'name' => 'name',
        ],
    ],

    // Route configuration
    'routes' => [
        'enabled' => true,
        'prefix' => 'cas',
        'middleware' => ['web'],
    ],

    // Logging configuration
    'logging' => [
        'enabled' => true,
        'channel' => 'single',
        'level' => 'info',
    ],
];
```

Middleware
----------

[](#middleware)

### CasAuthentication Middleware

[](#casauthentication-middleware)

Protects routes requiring CAS authentication:

```
Route::middleware(['cas.auth'])->group(function () {
    Route::get('/protected', [Controller::class, 'method']);
});
```

### CasRole Middleware

[](#casrole-middleware)

Protects routes requiring specific roles:

```
// Single role
Route::middleware(['cas.auth', 'cas.role:admin'])->group(function () {
    Route::get('/admin', [AdminController::class, 'index']);
});

// Multiple roles (user needs ANY of these roles)
Route::middleware(['cas.auth', 'cas.role:admin,manager,supervisor'])->group(function () {
    Route::get('/management', [ManagementController::class, 'index']);
});
```

API Reference
-------------

[](#api-reference)

### CasAuthService Methods

[](#casauthservice-methods)

```
// Get CAS login URL
$loginUrl = CasClient::getLoginUrl($returnUrl);

// Validate authentication token
$user = CasClient::validateToken($token);

// Get cached user data
$user = CasClient::getUserFromToken($token);

// Logout from CAS server
$success = CasClient::logout($token);

// Role checking methods
$hasRole = CasClient::userHasRole($user, 'admin');
$hasAnyRole = CasClient::userHasAnyRole($user, ['admin', 'manager']);
$hasAllRoles = CasClient::userHasAllRoles($user, ['user', 'verified']);
```

### User Data Structure

[](#user-data-structure)

```
$user = [
    'id' => 1,
    'username' => 'john_doe',
    'email' => 'john@example.com',
    'name' => 'John Doe',
    'roles' => ['user', 'manager'],
    // Additional fields from CAS server
];
```

Security Features
-----------------

[](#security-features)

### Signature Validation

[](#signature-validation)

When enabled, all requests to the CAS server are signed with HMAC SHA-256:

```
// Automatic signature generation
$signature = hash_hmac('sha256', $payload, $secret);
```

The payload includes:

- HTTP method
- Request URI
- Request body
- Timestamp
- Client ID

### Token Caching

[](#token-caching)

User data is cached to reduce CAS server load:

```
// Cached for performance
Cache::put("cas_user_{$token}", $userData, $ttl);
```

### Error Handling

[](#error-handling)

Comprehensive error handling for all CAS operations:

```
try {
    $user = CasClient::validateToken($token);
} catch (CasAuthException $e) {
    Log::error('CAS authentication failed', ['error' => $e->getMessage()]);
}
```

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

[](#troubleshooting)

### Common Issues

[](#common-issues)

1. **Authentication Loop**

    - Check `CAS_CALLBACK_URL` matches your route
    - Verify session configuration
    - Ensure middleware order is correct
2. **Token Validation Fails**

    - Verify client credentials in CAS server
    - Check `CAS_SIGNATURE_SECRET` if using signatures
    - Ensure CAS server is accessible
3. **Role Access Denied**

    - Verify user has required roles in CAS
    - Check role middleware configuration
    - Ensure roles are properly synced

### Debug Mode

[](#debug-mode)

Enable debug logging:

```
CAS_LOGGING_ENABLED=true
CAS_LOG_LEVEL=debug
```

### Testing

[](#testing)

Test your configuration:

```
# Test CAS server connectivity
curl -I http://your-cas-server.com/health

# Test token validation
php artisan tinker
>>> app(CasAuthService::class)->validateToken('your-test-token');
```

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

Support
-------

[](#support)

For support, visit [innovativesolution.com.np](https://innovativesolution.com.np/) or [create an issue](https://github.com/insol-dev/central-authentication-server/issues) on GitHub.

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

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this package.

Changelog
---------

[](#changelog)

Please see [CHANGELOG.md](CHANGELOG.md) for details on recent changes.

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance91

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Every ~43 days

Total

2

Last Release

41d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/067422ba68224b21390e88705475315e2a909c9d407380b5e412ffe20da8eefd?d=identicon)[rkalyan01](/maintainers/rkalyan01)

---

Top Contributors

[![rkalyan01](https://avatars.githubusercontent.com/u/4374994?v=4)](https://github.com/rkalyan01 "rkalyan01 (3 commits)")

---

Tags

jwtlaravelAuthenticationSSOcassingle sign onhmaccentral-authentication

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/insol-dev-central-authentication-server/health.svg)

```
[![Health](https://phpackages.com/badges/insol-dev-central-authentication-server/health.svg)](https://phpackages.com/packages/insol-dev-central-authentication-server)
```

###  Alternatives

[ellaisys/aws-cognito

Laravel Authentication using AWS Cognito (Web and API)

123256.9k1](/packages/ellaisys-aws-cognito)[google/auth

Google Auth Library for PHP

1.4k294.2M215](/packages/google-auth)[statamic/cms

The Statamic CMS Core Package

4.8k3.6M946](/packages/statamic-cms)[unopim/unopim

UnoPim Laravel PIM

10.5k2.2k](/packages/unopim-unopim)

PHPackages © 2026

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