PHPackages                             adithwidhiantara/laravel-anyauth - 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. adithwidhiantara/laravel-anyauth

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

adithwidhiantara/laravel-anyauth
================================

Auth from Anywhere!

1.0.0(3mo ago)00MITPHPPHP ^8.1CI passing

Since Jan 26Pushed 3mo agoCompare

[ Source](https://github.com/adith-widhiantara/laravel-anyauth)[ Packagist](https://packagist.org/packages/adithwidhiantara/laravel-anyauth)[ RSS](/packages/adithwidhiantara-laravel-anyauth/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (2)Used By (0)

Laravel AnyAuth 🛡️
==================

[](#laravel-anyauth-️)

[![codecov](https://camo.githubusercontent.com/c67f738e6556cb0a84e23c5c28211018d0dbb18312dc39f0749a598ea802b0a7/68747470733a2f2f636f6465636f762e696f2f6769746875622f61646974682d7769646869616e746172612f6c61726176656c2d616e79617574682f67726170682f62616467652e7376673f746f6b656e3d49354c544455394d4454)](https://codecov.io/github/adith-widhiantara/laravel-anyauth)

**The Flexible, Schema-Agnostic, and Multi-Provider Authorization Package for Laravel.**

**Laravel AnyAuth** is not just another permission package. Unlike traditional solutions that force a specific database structure upon you, AnyAuth adapts to **your** existing database schema. It also introduces a "Virtual Provider" system, allowing you to fetch permissions from APIs, Microservices, or Config files, not just the database.

🚀 Key Features
--------------

[](#-key-features)

- **Schema Agnostic:** Use your existing legacy tables (`user_groups`, `rights`, etc.). No need to migrate data to new tables.
- **Multi-Provider Chain:** Check permissions from multiple sources (Config -&gt; API -&gt; Database) in a prioritized chain.
- **Virtual Permissions:** Fetch permissions from external APIs (SSO, Microservices) with built-in caching.
- **Time-Bound Roles:** Assign temporary roles that expire automatically (e.g., "VIP for 7 days").
- **Role Hierarchy:** Supports recursive role inheritance (Parent -&gt; Child roles).
- **Transactional Safety:** Atomic operations for assigning/removing roles.
- **Fail-Fast Architecture:** Detects configuration errors immediately without crashing your runtime unnecessarily.

---

📦 Installation
--------------

[](#-installation)

Install the package via composer:

```
composer require adith-widhiantara/laravel-anyauth
```

Publish the configuration file (Crucial step):

```
php artisan vendor:publish --tag=anyauth-config
```

(Optional) If you don't have existing tables and want a fresh start, publish the default migrations:

```
php artisan vendor:publish --tag=anyauth-migrations
php artisan migrate
```

---

⚙️ Configuration (The Magic Part)
---------------------------------

[](#️-configuration-the-magic-part)

The power of AnyAuth lies in `config/anyauth.php`. Here you map the package logic to your database structure.

### 1. Mapping Your Database

[](#1-mapping-your-database)

If you have an existing database, simply point the config to your table names:

```
// config/anyauth.php

'tables' => [
    'roles' => 'master_jabatan',             // Your roles table
    'permissions' => 'master_hak_akses',     // Your permissions table
    'model_has_roles' => 'users_jabatan',    // Your pivot table
    'role_has_permissions' => 'jabatan_hak', // Your pivot table
],

'columns' => [
    'role_name' => 'nama_jabatan',           // Column for role name (e.g., 'manager')
    'permission_name' => 'kode_akses',       // Column for permission slug (e.g., 'edit-post')
    'model_morph_key' => 'user_id',          // Foreign key for User
    'role_foreign_key' => 'jabatan_id',      // Foreign key for Role

    // Advanced Features
    'pivot_expires_at' => 'valid_until',     // Column for expiration date (optional)
    'role_parent_key' => 'parent_id',        // Column for hierarchy (optional)
],
```

### 2. Defining Providers

[](#2-defining-providers)

You can define the order of authority. The system checks providers from top to bottom.

```
'providers' => [
    // 1. Check Config (God Mode)
    \AnyAuth\Providers\ConfigPermissionProvider::class,

    // 2. Check External API (Custom Provider)
    \App\Providers\YourCompanySsoProvider::class,

    // 3. Check Database (Default)
    \AnyAuth\Providers\DatabasePermissionProvider::class,
],
```

---

📖 Basic Usage
-------------

[](#-basic-usage)

### 1. Setup Model

[](#1-setup-model)

Add the `HasDynamicPermissions` trait to your User model.

```
use Illuminate\Foundation\Auth\User as Authenticatable;
use AnyAuth\Traits\HasDynamicPermissions;

class User extends Authenticatable
{
    use HasDynamicPermissions;
}
```

### 2. Checking Permissions

[](#2-checking-permissions)

AnyAuth hooks directly into Laravel's `Gate`. You can use standard Laravel authorization methods.

```
// In Controller
if ($user->can('edit-post')) {
    // ...
}

// In Blade
@can('edit-post')
    Edit
@endcan
```

### 3. Assigning Roles (Write Access)

[](#3-assigning-roles-write-access)

You can assign roles to users using the trait methods. This works regardless of your table names.

```
// Assign a role
$user->assignRole('manager');

// Remove a role
$user->removeRole('intern');
```

---

🔥 Advanced Features
-------------------

[](#-advanced-features)

### ⏳ Time-Bound Permissions (Temporary Access)

[](#-time-bound-permissions-temporary-access)

Give a user a role for a specific duration. Once the time passes, `can()` will automatically return `false`.

```
// Grant 'editor' role for 7 days only
$user->assignRole('editor', now()->addDays(7));
```

*Note: Ensure your pivot table has the expiration column defined in `config/anyauth.php`.*

### 🌳 Role Hierarchy

[](#-role-hierarchy)

If your roles table has a parent-child relationship (e.g., `parent_id`), AnyAuth can resolve permissions recursively.

- **Scenario:** `Director` is parent of `Manager`. `Manager` is parent of `Staff`.
- **Result:** A user assigned as `Director` automatically inherits all permissions from `Manager` and `Staff`.

Enable this in config:

```
'settings' => [
    'enable_hierarchy' => true,
],
```

### ⚡ Super Admin (God Mode)

[](#-super-admin-god-mode)

You can define emails that have access to **everything**, bypassing database checks. Useful for developers.

```
// config/anyauth.php
'super_admins' => [
    'dev@yourcompany.com',
    'root@localhost',
],
```

---

🔌 Virtual Providers (External APIs)
-----------------------------------

[](#-virtual-providers-external-apis)

Need to check permissions from an external Microservice or SSO? You don't need to sync data to your local database. Use a Virtual Provider.

### 1. Generate a Provider

[](#1-generate-a-provider)

Run the artisan command to create a boilerplate provider:

```
php artisan anyauth:make-provider YourCompanySsoProvider
```

### 2. Implement Logic

[](#2-implement-logic)

Edit `app/Providers/YourCompanySsoProvider.php`. AnyAuth handles caching automatically for you!

```
namespace App\Providers;

use AnyAuth\Providers\AbstractApiPermissionProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Facades\Http;

class YourCompanySsoProvider extends AbstractApiPermissionProvider
{
    protected function fetchPermissions(Authenticatable $user): array
    {
        // Example: Call external API
        $response = Http::withToken($user->token)->get('https://api.internal.com/my-access');

        // Return simple array of permission strings
        // e.g., ['can_edit', 'can_delete']
        return $response->json('data.permissions', []);
    }
}
```

### 3. Register It

[](#3-register-it)

Add your new class to the `providers` array in `config/anyauth.php`.

---

🧠 Architecture Concepts
-----------------------

[](#-architecture-concepts)

### Chain of Responsibility

[](#chain-of-responsibility)

AnyAuth uses a prioritized chain. Each provider returns one of three states:

1. **TRUE:** Access Granted. Stop checking.
2. **FALSE:** Access Denied. Stop checking.
3. **NULL:** Neutral / Abstain. Continue to the next provider.

### Performance

[](#performance)

- **No Eloquent Overhead:** Database checks use raw fluent queries (`DB::table`), making it significantly faster than loading Eloquent models.
- **Auto-Caching:** API Providers implement automatic caching (TTL configurable) to prevent slowing down your request lifecycle.

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License
---------

[](#-license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance80

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Unknown

Total

1

Last Release

107d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a9fcb175983dc323f8c81f4204771a22e22477fba78c30a3961b252c1a41619b?d=identicon)[adith-widhiantara](/maintainers/adith-widhiantara)

---

Top Contributors

[![adith-widhiantara](https://avatars.githubusercontent.com/u/54925429?v=4)](https://github.com/adith-widhiantara "adith-widhiantara (15 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/adithwidhiantara-laravel-anyauth/health.svg)

```
[![Health](https://phpackages.com/badges/adithwidhiantara-laravel-anyauth/health.svg)](https://phpackages.com/packages/adithwidhiantara-laravel-anyauth)
```

###  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)
