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

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

unicoart/slim-token-authentication
==================================

Slim 3.0+ Token Authentication Middleware

080PHP

Since Jan 18Pushed 7y ago1 watchersCompare

[ Source](https://github.com/LogIN-/slim-token-authentication)[ Packagist](https://packagist.org/packages/unicoart/slim-token-authentication)[ RSS](/packages/unicoart-slim-token-authentication/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (1)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 unicoart/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
    ...

};

$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

20

—

LowBetter than 14% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity38

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/981e8925fef9a0e5a8aa78c246f424162a467458318befd9f985c3332936fb30?d=identicon)[LogIN-](/maintainers/LogIN-)

---

Top Contributors

[![LogIN-](https://avatars.githubusercontent.com/u/4036277?v=4)](https://github.com/LogIN- "LogIN- (1 commits)")

### Embed Badge

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

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

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