PHPackages                             mycodebox/slim-token-authentication - 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. mycodebox/slim-token-authentication

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

mycodebox/slim-token-authentication
===================================

Slim 3.0+ Token Authentication Middleware

0.3.5(10mo ago)02MITPHPPHP &gt;=5.4.0

Since Jul 9Pushed 10mo agoCompare

[ Source](https://github.com/myCodebox/slim-token-authentication)[ Packagist](https://packagist.org/packages/mycodebox/slim-token-authentication)[ Docs](https://github.com/mycodebox/slim-token-authentication)[ RSS](/packages/mycodebox-slim-token-authentication/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (3)Versions (3)Used By (0)

Slim Token Authentication
=========================

[](#slim-token-authentication)

This is a Token Authentication Middleware for Slim 3.0+. This middleware was designed to maintain easy to implement token authentication with custom authenticator.

Installing
----------

[](#installing)

Get the latest version with [Composer](http://getcomposer.org "Composer").

```
composer require mycodebox/slim-token-authentication
```

Getting authentication
----------------------

[](#getting-authentication)

Start by creating an `authenticator` function, this function will make the token validation of your application. When you create a new instance of `TokenAuthentication` you must pass an array with configuration options. You need setting authenticator and path options for authentication to start working.

```
$authenticator = function($request, TokenAuthentication $tokenAuth){

    # Search for token on header, parameter, cookie or attribute
    $token = $tokenAuth->findToken($request);

    # Your method to make token validation
    $user = User::auth_token($token);

    # If occured ok authentication continue to route
    # before end you can storage the user informations or whatever
    return $request->withAttribute('auth_current_user', $auth->getUserByToken($token));
};

$app = new App();

$app->add(new TokenAuthentication([
    'path' => '/api',
    'authenticator' => $authenticator
]));
```

### Find Token

[](#find-token)

This middleware contains the method `findToken()`, you can access it from your authenticator method through the second param (`TokenAuthentication` instance). This method is able to search for authentication token on header, parameter, cookie or attribute. You can configure it through options settings.

Configuration Options
---------------------

[](#configuration-options)

### Path

[](#path)

By default no route requires authentication. You must set one or more routes to be restricted by authentication, setting it on `path` option.

```
...

$app = new App();

$app->add(new TokenAuthentication([
    'path' => '/api', /* or ['/api', '/docs'] */
    'authenticator' => $authenticator
]));
```

### Passthrough

[](#passthrough)

You can configure which routes do not require authentication, setting it on `passthrough` option.

```
...

$app = new App();

$app->add(new TokenAuthentication([
    'path' => '/api',
    'passthrough' => '/api/auth', /* or ['/api/auth', '/api/test'] */
    'authenticator' => $authenticator
]));
```

### Header

[](#header)

By default middleware tries to find token from `Authorization` header. You can change header name using `header` option. Is expected in Authorization header the value format as `Bearer `, it is matched using a regular expression. If you want to work without token type or with other token type, like `Basic `, you can change the regular expression pattern setting it on `regex` option. You can disabled authentication via header by setting `header` option as null.

```
...

$app->add(new TokenAuthentication([
    'path' => '/api',
    'authenticator' => $authenticator,
    'header' => 'Token-Authorization-X',
    'regex' => '/Basic\s+(.*)$/i', /* for without token type can use /\s+(.*)$/i */
]));
```

### Parameter

[](#parameter)

If token is not found in header, middleware tries to find `authorization` query parameter. You can change parameter name using `parameter` option. You can disable authentication via parameter by setting `parameter` option as null.

```
...

$app->add(new TokenAuthentication([
    'path' => '/api',
    'authenticator' => $authenticator,
    'parameter' => 'token'
]));
```

### Cookie

[](#cookie)

If token is not found yet, middleware tries to find `authorization` cookie. You can change cookie name using `cookie` option. You can disabled authentication via cookie by setting `cookie` option as null.

```
...

$app->add(new TokenAuthentication([
    'path' => '/api',
    'authenticator' => $authenticator,
    'cookie' => 'token'
]));
```

### Argument

[](#argument)

As a last resort, middleware tries to find `authorization` argument of route. You can change argument name using `argument` option. You can disabled authentication via argument by setting `argument` option as null.

```
...

$app->add(new TokenAuthentication([
    'path' => '/api',
    'authenticator' => $authenticator,
    'argument' => 'token'
]));
```

### Error

[](#error)

By default on ocurred a fail on authentication, is sent a response on json format with a message (`Invalid Token` or `Not found Token`) and with the token (if found), with status `401 Unauthorized`. You can customize it by setting a callable function on `error` option.

```
...

$error = function($request, $response, TokenAuthentication $tokenAuth) {
    $output = [];
    $output['error'] = [
        'msg' => $tokenAuth->getResponseMessage(),
        'token' => $tokenAuth->getResponseToken(),
        'status' => 401,
        'error' => true
    ];
    return $response->withJson($output, 401);
}

$app = new App();

$app->add(new TokenAuthentication([
    'path' => '/api',
    'authenticator' => $authenticator
    'error' => $error
]));
```

This error function is called when `TokenAuthentication` catches a throwable class that implements `UnauthorizedExceptionInterface`.

### Secure

[](#secure)

Tokens are essentially passwords. You should treat them as such and you should always use HTTPS. If the middleware detects insecure usage over HTTP it will return unathorized with a message `Required HTTPS for token authentication`. This rule is relaxed for requests on localhost. To allow insecure usage you must enable it manually by setting `secure` to false.

```
...

$app = new App();

$app->add(new TokenAuthentication([
    'path' => '/api',
    'authenticator' => $authenticator,
    'secure' => false
]));
```

Alternatively you can list your development host to have `relaxed` security.

```
...

$app->add(new TokenAuthentication([
    'path' => '/api',
    'authenticator' => $authenticator,
    'secure' => true,
    'relaxed' => ['localhost', 'your-app.dev']
]));
```

Example
-------

[](#example)

See how use it on [/example](example).

License
-------

[](#license)

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

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance54

Moderate activity, may be stable

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity22

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 ~6 days

Total

2

Last Release

307d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/19c8dbeacdd046cee91c9a752d6469269b6f1bac36c1eb72a6490a6cffe952c8?d=identicon)[myCodebox](/maintainers/myCodebox)

---

Top Contributors

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

---

Tags

middlewareauthAuthenticationslimtokenauthorization

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/mycodebox-slim-token-authentication/health.svg)

```
[![Health](https://phpackages.com/badges/mycodebox-slim-token-authentication/health.svg)](https://phpackages.com/packages/mycodebox-slim-token-authentication)
```

###  Alternatives

[league/oauth2-server

A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.

6.6k136.0M248](/packages/league-oauth2-server)[dyorg/slim-token-authentication

Slim 3.0+ Token Authentication Middleware

78106.5k](/packages/dyorg-slim-token-authentication)[auth0/auth0-php

PHP SDK for Auth0 Authentication and Management APIs.

40820.2M68](/packages/auth0-auth0-php)[auth0/login

Auth0 Laravel SDK. Straight-forward and tested methods for implementing authentication, and accessing Auth0's Management API endpoints.

2745.0M3](/packages/auth0-login)[jeremykendall/slim-auth

Authorization and authentication for the Slim Framework using ZF2 Authentication and Acl components

24824.6k](/packages/jeremykendall-slim-auth)[dereuromark/cakephp-tinyauth

A CakePHP plugin to handle user authentication and authorization the easy way.

129228.6k10](/packages/dereuromark-cakephp-tinyauth)

PHPackages © 2026

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