PHPackages                             luk-z/php-api-token-auth - 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. luk-z/php-api-token-auth

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

luk-z/php-api-token-auth
========================

Simple PHP REST API token-based authentication

v0.1.18(3y ago)1841MITPHP

Since Dec 6Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/lukzed/php-api-token-auth)[ Packagist](https://packagist.org/packages/luk-z/php-api-token-auth)[ Docs](https://github.com/Luk-z/php-api-token-auth)[ RSS](/packages/luk-z-php-api-token-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (40)Used By (1)

Php Api Token Authentication
============================

[](#php-api-token-authentication)

This library is based on

Install
-------

[](#install)

### Composer

[](#composer)

```
composer require luk-z/php-api-token-auth
```

### Manual

[](#manual)

Donwload ad extract source code from github, then include in you project:

```
require_once SDIM_LIB_PATA_DIR.'/index.php';
```

Developing
----------

[](#developing)

### Requirements

[](#requirements)

To install dependencies php 7.3+ and composer are needed. Instead installing them in the local machine use a dockerized composer (requires Docker Desktop).

Create `php` and `composer` aliases following [this guide](https://github.com/lukzed/dockerized-composer).

### Install php-cs-fixer

[](#install-php-cs-fixer)

```
composer require --working-dir=tools/php-cs-fixer friendsofphp/php-cs-fixer
```

### Install dependencies

[](#install-dependencies)

```
composer install
```

Run test
--------

[](#run-test)

If composer and php are dockerized use this command

```
php app/vendor/bin/phpunit /app/tests
```

else use this command

```
vendor/bin/phpunit
```

Use in project
==============

[](#use-in-project)

```
composer create-project --prefer-dist laravel/lumen:^8 lumen-api.luca.ziliani.me
composer require luk-z/php-api-token-auth
```

TODO
----

[](#todo)

-  see
- changelog
- .editorconfig

PHP CS Fixer
------------

[](#php-cs-fixer)

To use correctly PHP CS Fixer copy `settings.json-example` to `settings.json` and insert absolute path of `tools/php-cs-fixer/vendor/bin/php-cs-fixer` to `php-cs-fixer.executablePath`

Release
-------

[](#release)

Repository is linked to packagist through (github web hook)\[\]. To push an update simply push a tag.

```
git tag v1.0.0 && git push origin v1.0.0
```

Functions
---------

[](#functions)

### PATA::init()

[](#patainit)

Initialize the library passing dome configuration information.

Params: TODO

Returns: void

### PATA::authenticate()

[](#pataauthenticate)

Take an access token and check if is valid/not expired

Params:

- `string` accessToken (required)
- `bool` checkExpired (optional): default to `true`

Returns:

- Success response

```
[
    "result" => true,
    "data" => ["sid" => string] // user session id
]
```

- Error response:

```
[
    "result" => false,
    "error" => [
        "message" => string,
        "code" => string,
        "fields" => array,
    ]
]
```

- Error codes:
    - PATA\_ERROR\_AUTH\_INVALID\_TOKEN
    - PATA\_ERROR\_AUTH\_TOKEN\_NOT\_FOUND
    - PATA\_ERROR\_AUTH\_TOKEN\_DUPLICATED
    - PATA\_ERROR\_AUTH\_TOKEN\_EXPIRED

### PATA::refreshToken()

[](#patarefreshtoken)

Takes an access token and refresh token and try to refresh a new access token. If refreshToken not passed try to get from cookies

Params:

- `string` accessToken (required)
- `string` refreshToken (required)

Returns:

- Success response

```
[
    "result" => true,
    "data" => [
        "sid" => string,
        "refreshToken" => string,
        "accessToken" => string,
        "debug" => [
            "setCookieResult" => string,
            "tokenInsertResult" => string,
            "deleteTokensResult" => string,
        ],
    ]
]
```

- Error response:

```
[
    "result" => false,
    "error" => [
        "message" => string,
        "code" => string,
        "fields" => array,
    ],
    "responseCode" => string, // suggested response code to return by endpoints
]
```

- Error codes:
    - ... all error codes returned by Authenticate
    - PATA\_ERROR\_REFRESH\_TOKEN\_INVALID - suggested response code=422
    - PATA\_ERROR\_REFRESH\_TOKEN\_NOT\_FOUND - suggested response code=401
    - PATA\_ERROR\_REFRESH\_TOKEN\_EXPIRED - suggested response code=401
    - PATA\_ERROR\_REFRESH\_TOKEN\_DIFFERENT\_SID - suggested response code=401
    - PATA\_ERROR\_REFRESH\_TOKEN\_DUPLICATED - suggested response code=401

### PATA::activate()

[](#pataactivate)

Searches provided activation token and check validity then set user activated and set activation token expired

Params:

- `string` accessToken (required)

Returns:

- Success response

```
[
    "result" => true,
    "data" => [
        "queryResult" => int, // affected row (should be 1)
        "userId" => int
    ]
]
```

- Error response:

```
[
    "result" => false,
    "error" => [
        "message" => string,
        "code" => string,
    ],
]
```

- Error codes:
    - PATA\_ERROR\_ACTIVATE\_TOKEN\_NOTFOUND
    - PATA\_ERROR\_ACTIVATE\_DUPLICATED\_TOKEN
    - PATA\_ERROR\_ACTIVATE\_TOKEN\_USED
    - PATA\_ERROR\_ACTIVATE\_TOKEN\_EXPIRED
    - PATA\_TOKEN\_EXPIRATION\_VALUE
    - PATA\_ERROR\_ACTIVATE\_TOKEN\_DB\_ERROR

### PATA::registerUser()

[](#pataregisteruser)

Creates a user with given email and password then send activation email. If user already exists.

Params:

- `string` email (required)
- `string` password (required)

Returns:

- Success response

```
[
    "result" => true,
    "data" => [
        "id" => int, // userId
        "shouldSendActivationEmail" => bool, // whether an activation email should be sent
        "activationToken" => "xxxxx", // user token for account activation
    ]
]
```

- Error response:

```
[
    "result" => false,
    "error" => [
        "message" => string,
        "code" => string,
        "fields" => ["id"=>int], // userId
    ],
]
```

- Error codes:
    - PATA\_ERROR\_REGISTRATION\_INVALID\_EMAIL
    - PATA\_ERROR\_REGISTRATION\_INVALID\_PASSWORD
    - PATA\_ERROR\_REGISTRATION\_EMAIL\_EXITSTS
    - PATA\_ERROR\_REGISTRATION\_CREATE

### PATA::loginUser()

[](#pataloginuser)

Check provided credentials then create a user session with refresh token, access token and session id. If provided credentials are wrong or usr isn't activated return an error

Params:

- `string` email (required)
- `string` password (required)

Returns:

- Success response

```
[
    "result" => true,
    "data"=>[
        "user" => array,
        "accessToken" => string,
        "sid" => string,
        "debug" => [
            "rtResult" => bool, // whether the set_cookie has succedeed
            "tokenInsertResult" => bool // whether the token is succesfully created in the database
        ],
    ]
]
```

- Error response:

```
[
    "result" => false,
    "error" => [
        "message" => string,
        "code" => string,
    ],
]
```

- Error codes:
    - PATA\_ERROR\_LOGIN\_INVALID\_EMAIL
    - PATA\_ERROR\_LOGIN\_INVALID\_PASSWORD
    - PATA\_ERROR\_WRONG\_EMAIL
    - PATA\_ERROR\_WRONG\_PASSWORD
    - PATA\_ERROR\_USER\_NOT\_ACTIVE

### PATA::logoutUser()

[](#patalogoutuser)

First executes authenticate() to check accessToken then delete user tokens associated to a specific sid

Params:

- `string` sid (required)
- `string` accessToken (required)

Returns:

- Success response

```
[
    "result" => true,
    "data" => [
        "queryResult" => int, // number of user session tokens deleted
    ]
]
```

- Error response:

```
[
    "result" => false,
    "error" => [
        "message" => string,
        "code" => string,
    ],
]
```

- Error codes:
    - ... all error codes returned by Authenticate

### PATA::forgotPassword()

[](#pataforgotpassword)

Check if email exists then send email with change password link (only if user is activated)

1. check email is valid
2. find active user
3. find change password tokens
    1. if expired, delete it
    2. if not expired return error

Params:

- `string` email (required)

Returns:

- Success response

```
[
    "result" => true,
    "data"=>[
        "changePasswordToken" => string,
        "shouldSendChangePasswordEmail" => string,
        "queryResult" => int,
    ]
]
```

- Error response:

```
[
    "result" => false,
    "error" => [
        "message" => string,
        "code" => string,
    ],
    "secondsLeft" => int // only if a valid token is already present, indicates the remaining seconds till token expiration
]
```

- Error codes:
    - PATA\_ERROR\_FORGOT\_PASSWORD\_INVALID\_EMAIL
    - PATA\_ERROR\_FORGOT\_PASSWORD\_ALREADY\_PRESENT

### PATA::changePassword()

[](#patachangepassword)

Check if password and token are valid then burn token and change password of the associated user (only if user is activated):

1. check password is valid
2. check token is valid and not expired
3. check user is active
4. check password is changed
5. change password in db
6. burn token

Params:

- `string` password (required)
- `string` token (required) - change password token

Returns:

- Success response

```
[
    "result" => true,
    "data" => [
        "queryResult" => boolean, // whether the user password is modified correctly
        "currentTokenDeleted" => int, // result of deleting current change password token (should be always 1)
        "accessTokenDeleted" => int, // number of access token deleted
        "refreshTokenDeleted" => int, // number of refresh token deleted
        "email" => int, // email of the current user
        "userId" => int, // id of the current user
    ]
]
```

- Error response:

```
[
    "result" => false,
    "error" => [
        "message" => string,
        "code" => string,
    ],
]
```

- Error codes:
    - PATA\_ERROR\_CHANGE\_PASSWORD\_INVALID\_PASSWORD
    - PATA\_ERROR\_CHANGE\_PASSWORD\_INVALID\_TOKEN
    - PATA\_ERROR\_CHANGE\_PASSWORD\_TOKEN\_NOT\_FOUND
    - PATA\_ERROR\_CHANGE\_PASSWORD\_TOKEN\_EXPIRED
    - PATA\_ERROR\_CHANGE\_PASSWORD\_PASSWORD\_NOT\_CHANGED
    - PATA\_ERROR\_CHANGE\_PASSWORD\_UPDATE\_USER

Usefull guides:

-
-
-

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance55

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity48

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

Total

39

Last Release

1201d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/55948cc6e05d34fe6bc3f96ce9d862bb421d28ef9a946051c90dccdad497017d?d=identicon)[lucagcc@gmail.com](/maintainers/lucagcc@gmail.com)

---

Top Contributors

[![Luk-z](https://avatars.githubusercontent.com/u/7655943?v=4)](https://github.com/Luk-z "Luk-z (59 commits)")

---

Tags

phpjwt

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/luk-z-php-api-token-auth/health.svg)

```
[![Health](https://phpackages.com/badges/luk-z-php-api-token-auth/health.svg)](https://phpackages.com/packages/luk-z-php-api-token-auth)
```

###  Alternatives

[griffinledingham/php-apple-signin

A simple library to decode and parse Apple Sign In client tokens.

2011.9M1](/packages/griffinledingham-php-apple-signin)[hyperf-ext/jwt

The Hyperf JWT package.

53134.9k2](/packages/hyperf-ext-jwt)[maicol07/flarum-ext-sso

SSO for Flarum

468.3k](/packages/maicol07-flarum-ext-sso)

PHPackages © 2026

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