PHPackages                             mcgo/laravel-barekey - 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. mcgo/laravel-barekey

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

mcgo/laravel-barekey
====================

Pure API key auth, nothing more, nothing less.

v1.0.3(4d ago)01.3k↓82.4%MITPHPCI failing

Since Oct 13Pushed 4d agoCompare

[ Source](https://github.com/McGo/laravel-barekey)[ Packagist](https://packagist.org/packages/mcgo/laravel-barekey)[ RSS](/packages/mcgo-laravel-barekey/feed)WikiDiscussions v1 Synced 3d ago

READMEChangelog (2)Dependencies (4)Versions (5)Used By (0)

🪶 Laravel Barekey
=================

[](#-laravel-barekey)

> **Authenticate everything – without users.**
> A minimal, stateless API key authentication guard for Laravel.
> No sessions. No Sanctum. No users. Just pure, verifiable keys.

---

🚀 Features
----------

[](#-features)

- 🧩 **Stateless API key guard** – powered by `Auth::viaRequest()`
- 🔐 **Secure hashing (SHA-256)** and prefix lookup for fast validation
- 🎯 **Abilities / Scopes** with wildcard support (`invoices:*`) - even as route middleware
- 🧠 **Enum-friendly design** for type-safe permission checks
- ⚡ **No database overhead** beyond a single table for all your api keys
- 🧱 **Works with Laravel Gates**, `Auth::check()`, and `auth:apikey` middleware

---

⛓️‍ Compatibility
-----------------

[](#️‍-compatibility)

Package VersionLaravel Versions1.x10.x, 11.x, 12.x---

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

[](#-installation)

```
composer require mcgo/laravel-barekey
```

Then run the migration:

```
php artisan migrate
```

⚙️ Setup
--------

[](#️-setup)

Register the guard in your `config/auth.php`. You can provide your custom Abilities Enum, see packages DefaultAbilities as example.

```
'guards' => [
    'barekey' => [
        'driver' => 'apikey',
        'provider' => null,
        // 'abilities' => YourAbilitiesEnum::class
    ],
],
```

Barekey automatically registers its guard in your `AuthServiceProvider`via `Auth::viaRequest('barekey', ...)`.

---

🔐 Keys
------

[](#-keys)

To generate new keys:

```
php artisan barekey:make "My Service api key" --abilities=invoices:read,reports:read
```

Output example:

```

API Key generated, please use it as the following header:
Authorization: Bearer 593acec5-d9c2-43dd-9155-d93bad8c49e4:CJalcoa3ukYpkHa2ZfTWnRi0s4q8JPslSiqKbWXkls1suHMkJ8Ya6ggOKEBoEFje
Or as custom header:
X-Barekey-Token: 593acec5-d9c2-43dd-9155-d93bad8c49e4:CJalcoa3ukYpkHa2ZfTWnRi0s4q8JPslSiqKbWXkls1suHMkJ8Ya6ggOKEBoEFje

```

---

🔑 Usage
-------

[](#-usage)

Protect routes using the built-in middleware:

```
Route::middleware('auth:barekey')->group(function () {
    Route::get('/status', fn() => ['ok' => true]);
});
```

You can also layer `can:` for ability-based checks:

```
Route::middleware(['auth:barekey', 'can:invoices:read'])
    ->get('/invoices', [InvoiceController::class, 'index']);
```

Inside your controller, you can access the authenticated key:

```
$key = request()->user(); // GenericUser with ->id, ->name, ->abilities
```

---

🧠 Abilities &amp; Gates
-----------------------

[](#-abilities--gates)

Define abilities as strings or Enums – both work:

```
Gate::before(function ($user, string $ability) {
    $abilities = (array) $user->abilities;
    return in_array('*', $abilities, true)
        || in_array($ability, $abilities, true)
        || str($abilities)->contains(fn($a) => str($ability)->isMatch($a));
});
```

Or use the included Enum helper:

```
use App\Enums\Ability;

Gate::before(fn($user, $ability) => Ability::granted($user->abilities, $ability));
```

---

🧮 Example Enum
--------------

[](#-example-enum)

```
namespace App\Enums;

use McGo\Barekey\Contracts\AbilitiesEnumContract;

enum Ability: string implements AbilitiesEnumContract
{
    case InvoicesRead  = 'invoices:read';
    case InvoicesWrite = 'invoices:write';
    case ReportsRead   = 'reports:read';
    case Admin         = 'admin';

    // Implement the needed methods.
}
```

---

🧼 Commands
----------

[](#-commands)

CommandDescription`php artisan barekey:make`Create a new API key---

🔒 Security Notes
----------------

[](#-security-notes)

- Always use HTTPS
- Never expose API keys in frontend code
- Rotate keys regularly
- Use `revoked_at` + `expires_at` to enforce lifecycle policies

---

🧪 Testing
---------

[](#-testing)

```
php artisan test
```

Example:

```
it('authenticates with valid API key', function () {
    $key = ApiKey::factory()->create([...]);

    $response = $this->withHeaders([
        'Authorization' => "Bearer {$key->plain}",
    ])->getJson('/api/status');

    $response->assertOk()->assertJson(['ok' => true]);
});
```

---

📋 Roadmap
---------

[](#-roadmap)

- Implement Commands to list and revoke key
- Implement rate limiting per key
- Add some events for created, revoked, used key and a rate limit that had hit

---

🧡 Credits
---------

[](#-credits)

- Inspired by [Laravel Sanctum](https://laravel.com/docs/sanctum),
    stripped to the essentials for user-free, machine-to-machine auth.
- Crafted by [McGo](https://github.com/McGo)

---

🪪 License
---------

[](#-license)

MIT © Mirko Haaser

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance99

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

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.

###  Release Activity

Cadence

Every ~65 days

Total

5

Last Release

4d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8d013a76b3f3fbb39055e2db159fe01f71efd504c0712308f776056da3ebddb7?d=identicon)[McGo](/maintainers/McGo)

---

Top Contributors

[![McGo](https://avatars.githubusercontent.com/u/278351?v=4)](https://github.com/McGo "McGo (2 commits)")

### Embed Badge

![Health badge](/badges/mcgo-laravel-barekey/health.svg)

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

###  Alternatives

[statamic-rad-pack/runway

Eloquently manage your database models in Statamic.

135224.7k7](/packages/statamic-rad-pack-runway)[jeremy379/laravel-openid-connect

OpenID Connect support to the PHP League's OAuth2 Server. Compatible with Laravel Passport.

59437.0k9](/packages/jeremy379-laravel-openid-connect)[api-platform/laravel

API Platform support for Laravel

58171.6k14](/packages/api-platform-laravel)[duncanmcclean/statamic-cargo

Comprehensive e-commerce addon for Statamic. Build bespoke e-commerce sites without the complexity.

3417.0k](/packages/duncanmcclean-statamic-cargo)

PHPackages © 2026

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