PHPackages                             keystackapp/keystack-php-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. keystackapp/keystack-php-auth

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

keystackapp/keystack-php-auth
=============================

KeyStack PHP library for data encryption and decryption, and login handling.

v0.0.3(6mo ago)04MITPHP

Since Oct 19Pushed 6mo agoCompare

[ Source](https://github.com/KeyStackApp/keystack-php-auth)[ Packagist](https://packagist.org/packages/keystackapp/keystack-php-auth)[ RSS](/packages/keystackapp-keystack-php-auth/feed)WikiDiscussions main Synced 1mo ago

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

PHP-encryptor
=============

[](#php-encryptor)

Keystack-php-auth is a small PHP library created for [keystack.app](https://keystack.app). This library provides functionalities to extract payloads from API keys, encrypt API keys, and create login input data from API keys for authentication purposes.

Installation
------------

[](#installation)

You can install the keystack-php-auth library via Composer:

```
composer require KeyStackApp/keystack-php-auth
```

Usage
-----

[](#usage)

Below are examples demonstrating how to use the library:

Extracting API Key Payload To extract the payload from a Keystack API key, use the `ApiKeyExtractor` class:

```
use KeyStackApp\Encryptor\ApiKeyExtractor;

$apiKeyExtractor = new ApiKeyExtractor();
$payload = $apiKeyExtractor->getApiKeyPayload($apiKey);
```

### Encrypting API Key

[](#encrypting-api-key)

To get the encrypted API key from the API key token, use the `KeyEncryptor` class:

```
use KeyStackApp\Encryptor\KeyEncryptor;

$keyEncryptor = new KeyEncryptor();
$encryptedApiKey = $keyEncryptor->getEncryptedApiKey($apiKey);
```

### Creating Login Input Data

[](#creating-login-input-data)

To create the login input data from the API key, use the `CredentialExtractor` class. This is the main functionality of the library, allowing the creation of login data from the API key for authentication:

```
use KeyStackApp\Encryptor\CredentialExtractor;

$credentialExtractor = new CredentialExtractor();
$loginInputData = $credentialExtractor->getLoginInputData($apiKey);
```

Token Storage Adapters
----------------------

[](#token-storage-adapters)

This library includes a set of pluggable adapters for storing short-lived JWT tokens and tracking login attempts. All adapters implement the same contract: `KeyStackApp\Adapter\TokenStorageAdapterInterface`.

Interface methods:

- storeToken(string $token): bool — persist a JWT token
- getToken(): ?string — retrieve the stored token if present
- clearToken(): bool — delete the stored token
- hasToken(): bool — check if a token is stored
- incrementLoginAttempt(): int — increment and return the login-attempt counter
- getLoginAttemptCount(): int — get current login-attempt count
- resetLoginAttemptCount(): bool — reset the login-attempt counter to 0

You can choose the adapter that fits your environment or implement your own.

### SessionAdapter (PHP native sessions)

[](#sessionadapter-php-native-sessions)

Namespace: `KeyStackApp\Adapter\SessionAdapter`

- Stores the token and login attempts in PHP session variables.
- Automatically starts the session if not already started.

Constructor:

- \_\_construct(string $sessionKey = 'keystack\_jwt\_token', string $loginAttemptKey = 'keystack\_login\_attempts')

Example:

```
use KeyStackApp\Adapter\SessionAdapter;

$adapter = new SessionAdapter();
$adapter->storeToken($jwt);
if ($adapter->hasToken()) {
    $token = $adapter->getToken();
}
$adapter->incrementLoginAttempt();
```

Notes:

- Ensure PHP session storage fits your scaling model (e.g., sticky sessions or external session handler for multi-node setups).

### FileAdapter (filesystem)

[](#fileadapter-filesystem)

Namespace: `KeyStackApp\Adapter\FileAdapter`

- Persists the token and login attempts as files on disk.
- Defaults to the system temp directory.

Constructor:

- \_\_construct(?string $storagePath = null, string $tokenFileName = 'keystack\_token', string $loginAttemptsFileName = 'keystack\_login\_attempts')

Example:

```
use KeyStackApp\Adapter\FileAdapter;

$adapter = new FileAdapter(__DIR__ . '/var/keystack');
$adapter->storeToken($jwt);
$count = $adapter->incrementLoginAttempt();
```

Notes:

- The directory must be writable by your PHP process.
- Suitable for single-host deployments or CLI scripts.

### RedisAdapter

[](#redisadapter)

Namespace: `KeyStackApp\Adapter\RedisAdapter`

- Stores data in Redis with TTL support.
- Requires the php-redis extension.

Constructor:

- \_\_construct(?\\Redis $redis = null, string $tokenKey = 'keystack:jwt\_token:', string $loginAttemptKey = 'keystack:login\_attempts:', int $ttl = 3600)

Behavior:

- If no \\Redis instance is provided, it connects to 127.0.0.1:6379 by default.
- Keys are set with expiration (TTL). Login-attempt counter also gets an expire.

Example:

```
use KeyStackApp\Adapter\RedisAdapter;

$redis = new \Redis();
$redis->connect('redis.internal', 6379);
$adapter = new RedisAdapter($redis, ttl: 1800);
$adapter->storeToken($jwt);
```

Notes:

- Prefer providing a pre-configured \\Redis instance (auth, database index, clustering, etc.).

### DatabaseAdapter (PDO)

[](#databaseadapter-pdo)

Namespace: `KeyStackApp\Adapter\DatabaseAdapter`

- Persists token and login attempts in a relational database using PDO.
- Creates the table automatically if it does not exist.

Constructor:

- \_\_construct(PDO $pdo, string $tableName = 'keystack\_tokens', string $keyIdentifier = 'default')

Schema (created automatically if missing):

- id VARCHAR(255) PRIMARY KEY
- token TEXT NULL
- login\_attempts INT DEFAULT 0
- created\_at TIMESTAMP DEFAULT CURRENT\_TIMESTAMP
- updated\_at TIMESTAMP DEFAULT CURRENT\_TIMESTAMP

Example:

```
use KeyStackApp\Adapter\DatabaseAdapter;

$pdo = new \PDO('mysql:host=localhost;dbname=app', 'user', 'pass', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
]);
$adapter = new DatabaseAdapter($pdo, keyIdentifier: 'user:123');
$adapter->storeToken($jwt);
$attempts = $adapter->getLoginAttemptCount();
```

Notes:

- keyIdentifier lets you store multiple tokens (one row per identifier). Choose a stable ID per context (user, tenant, etc.).
- Ensure proper DB privileges and connection error handling.

### WPTransientAdapter (WordPress)

[](#wptransientadapter-wordpress)

Namespace: `KeyStackApp\Adapter\WPTransientAdapter`

- Uses WordPress transients API to store the token and login attempts with TTLs.
- Requires a WordPress environment (functions: set\_transient, get\_transient, delete\_transient).

Constructor:

- \_\_construct(string $tokenKey = 'keystack\_jwt\_token', string $loginAttemptKey = 'keystack\_login\_attempts', int $tokenTtl = 3600, int $loginAttemptTtl = 86400)

Example:

```
use KeyStackApp\Adapter\WPTransientAdapter;

$adapter = new WPTransientAdapter(tokenTtl: 3600, loginAttemptTtl: 86400);
$adapter->storeToken($jwt);
```

Notes:

- Transients are cached with expiration; persistence depends on the site's object cache setup.

### Implementing a custom adapter

[](#implementing-a-custom-adapter)

1. Create a class that implements `KeyStackApp\Adapter\TokenStorageAdapterInterface`.
2. Implement all required methods to match your storage backend (memcached, Laravel cache, etc.).
3. Keep tokens short-lived and clear them when no longer needed.

Skeleton:

```
use KeyStackApp\Adapter\TokenStorageAdapterInterface;

class MyCacheAdapter implements TokenStorageAdapterInterface {
    public function storeToken(string $token): bool { /* ... */ }
    public function getToken(): ?string { /* ... */ }
    public function clearToken(): bool { /* ... */ }
    public function hasToken(): bool { /* ... */ }
    public function incrementLoginAttempt(): int { /* ... */ }
    public function getLoginAttemptCount(): int { /* ... */ }
    public function resetLoginAttemptCount(): bool { /* ... */ }
}
```

### Security considerations

[](#security-considerations)

- Treat the JWT token as sensitive data; prefer memory or secure stores when possible.
- Apply appropriate TTLs to reduce risk of token leakage.
- For multi-user contexts, use distinct keys/identifiers per principal.

License
-------

[](#license)

This project is licensed under the MIT License. See the [LICENSE](https://github.com/KeyStackApp/keystack-php-auth/blob/main/LICENSE) file for details.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance68

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity27

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

Total

3

Last Release

188d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/458d0f814dd1c74d8f025f23472a60b25970706a2ed2a00027c8bbf415602f82?d=identicon)[keystack.app](/maintainers/keystack.app)

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/keystackapp-keystack-php-auth/health.svg)

```
[![Health](https://phpackages.com/badges/keystackapp-keystack-php-auth/health.svg)](https://phpackages.com/packages/keystackapp-keystack-php-auth)
```

###  Alternatives

[web-auth/webauthn-framework

FIDO2/Webauthn library for PHP and Symfony Bundle.

50570.7k1](/packages/web-auth-webauthn-framework)[web-auth/webauthn-symfony-bundle

FIDO2/Webauthn Security Bundle For Symfony

63397.4k6](/packages/web-auth-webauthn-symfony-bundle)[clerkinc/backend-php

2755.0k](/packages/clerkinc-backend-php)[jakub-onderka/openid-connect-php

Bare-bones OpenID Connect client

1151.4k](/packages/jakub-onderka-openid-connect-php)

PHPackages © 2026

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