PHPackages                             jdz/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. jdz/authentication

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

jdz/authentication
==================

Basic Authentication Library

3.6.4(2mo ago)043MITPHPPHP &gt;=8.2

Since Dec 3Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/joffreydemetz/authentication)[ Packagist](https://packagist.org/packages/jdz/authentication)[ Docs](https://jdz.joffreydemetz.com/authentication)[ RSS](/packages/jdz-authentication/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (6)Versions (13)Used By (0)

JDZ Authentication
==================

[](#jdz-authentication)

Simple authentication library with support for multiple authentication connectors.

Features
--------

[](#features)

- Multiple authentication connectors support
- Type-safe authentication status enum
- PDO-based database authentication
- Basic authentication connector
- Extensible connector interface
- Comprehensive test suite
- Automatic password hashing
- Secure password verification

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

[](#installation)

```
composer require jdz/authentication
```

Requirements
------------

[](#requirements)

- PHP 8.1 or higher

Quick Start
-----------

[](#quick-start)

```
use JDZ\Authentication\Authentication;
use JDZ\Authentication\Connector\BasicConnector;

$auth = new Authentication();
$auth->addConnector(new BasicConnector('admin', 'secret123'));

$result = $auth->authenticate([
    'identifier' => 'admin',
    'password' => 'secret123',
]);

if ($result->isSuccess()) {
    echo "Welcome, " . $result->getUsername();
} else {
    echo "Error: " . $result->getMessage();
}
```

Examples
--------

[](#examples)

All examples can be run directly from the command line:

**Note**: Examples 03 and 05 require PDO SQLite extension. If not available, you can:

1. Enable `pdo_sqlite` in your `php.ini`, OR
2. Modify the examples to use MySQL/PostgreSQL (see Database Setup Notes below)

Check available PDO drivers: `php -m | grep -i pdo`

See the [examples](examples/) directory for detailed examples:

- `01-basic-authentication.php` - Basic authentication
- `02-multiple-connectors.php` - Multiple authentication connectors
- `03-database-authentication.php` - Database authentication with PDO (requires PDO SQLite)
- `04-error-handling.php` - Error handling with exceptions
- `05-advanced-mysql.php` - Advanced MySQL authentication (requires PDO SQLite or MySQL)

Run example:

```
php examples/01-basic-authentication.php
```

### 01-basic-authentication.php

[](#01-basic-authenticationphp)

**Basic Authentication with BasicConnector**

Demonstrates:

- Creating a basic authentication instance
- Using BasicConnector for simple identifier/password authentication
- Testing various authentication scenarios (valid, invalid, missing credentials)
- Checking authentication status and error messages

**Use Case**: Simple applications with hardcoded or configuration-based credentials.

---

### 02-multiple-connectors.php

[](#02-multiple-connectorsphp)

**Multiple Authentication Connectors**

Demonstrates:

- Adding multiple connectors to a single authentication instance
- How connectors are tried by priority order
- Authenticating different users with different credentials
- Converting result to array format

**Use Case**: Applications supporting multiple authentication methods or user sources.

---

### 03-database-authentication.php

[](#03-database-authenticationphp)

**Database Authentication with PDO**

Demonstrates:

- Creating a custom connector by extending AbstractConnector
- Using PDO for database queries
- Storing and verifying hashed passwords
- Setting up and testing with SQLite (easily adaptable to MySQL/PostgreSQL)
- Proper SQL prepared statements for security

**Use Case**: Standard web applications with user accounts stored in a database.

**Key Points**:

- Uses `password_hash()` and `password_verify()` for secure password storage
- Demonstrates proper PDO usage with prepared statements
- Shows how to create custom connectors

---

### 04-error-handling.php

[](#04-error-handlingphp)

**Error Handling with Exceptions**

Demonstrates:

- Using the built-in AuthenticationException
- Proper exception handling patterns
- Silent mode authentication (without exceptions)
- Custom error message mapping
- Using AuthStatusEnum for detailed error information

**Use Case**: Production applications requiring robust error handling and user-friendly error messages.

**Key Points**:

- Shows how to extract status codes and messages from exceptions
- Demonstrates both exception and return-value error handling patterns
- Custom error message mapping for better UX

---

### 05-advanced-mysql.php

[](#05-advanced-mysqlphp)

**Advanced MySQL Authentication with User Data**

Demonstrates:

- Advanced custom connector with additional features
- Loading user profile data during authentication
- Checking user account status (active/inactive)
- Populating AuthenticationResult with user details
- Production-ready MySQL connector implementation

**Use Case**: Full-featured applications requiring user profile data, account status checks, and multi-language support.

**Key Points**:

- Shows how to implement custom authenticate() method
- Demonstrates loading additional user data
- Includes account status validation
- Multi-language support example

---

Database Setup Notes
--------------------

[](#database-setup-notes)

For examples using databases:

**SQLite** No setup required - creates in-memory database automatically.

Testing
-------

[](#testing)

```
# Run all tests
composer test

# Or use PHPUnit directly
vendor/bin/phpunit
```

The test suite includes **59 tests** with **143 assertions**:

- **AuthStatusEnumTest** (9 tests): Tests for the authentication status enum values and methods
- **AuthenticationResultTest** (12 tests): Tests for the authentication result object, factory methods, and toArray() conversion
- **AuthenticationTest** (13 tests): Tests for the main authentication class including credentials normalization, priority, and connector flow
- **BasicConnectorTest** (11 tests): Tests for the basic authentication connector including constructor validation and authentication scenarios
- **DatabaseConnectorTest** (14 tests): Tests for the database authentication connector using mocked DatabaseInterface

Authentication Status
---------------------

[](#authentication-status)

The library uses `AuthStatusEnum` for type-safe status handling:

StatusValueDescription`FAILURE`0Authentication failed (generic)`SUCCESS`1Successful authentication`EMPTY_IDENTIFIER`2Missing identifier (email/username) in credentials`EMPTY_PASSWORD`3Missing password in credentials`USER_NOT_FOUND`4User account not found`INVALID_PASSWORD`5Invalid password`USER_BANNED`6Account has been suspended`USER_NOT_CONFIRMED`7Email not confirmed`ACCOUNT_LOCKED`8Account locked due to failed attemptsEach status provides:

- `value` - Returns the integer status code
- `message()` - Returns the descriptive error message
- `isSuccess()` - Returns true only for SUCCESS status
- `name` - The enum case name (e.g., "SUCCESS", "INVALID\_PASSWORD")

Example usage:

```
$result = $auth->authenticate($credentials);

if ($result->isSuccess()) {
    echo "User ID: " . $result->getUserId();
    echo "Email: " . $result->getEmail();
} else {
    echo "Status Code: " . $result->getStatus()->value;      // 5
    echo "Message: " . $result->getStatus()->message();      // "Invalid password"
    echo "Name: " . $result->getStatus()->name;              // "INVALID_PASSWORD"
}
```

AuthenticationResult
--------------------

[](#authenticationresult)

The `AuthenticationResult` object provides the following methods:

```
$result->isSuccess();       // bool - Check if authentication succeeded
$result->getStatus();       // AuthStatusEnum - Get the status enum
$result->getMessage();      // string - Get error message (or status message)
$result->getUserId();       // ?int - Get user ID (if available)
$result->getIdentifier();   // string - Get the identifier used
$result->getEmail();        // string - Get user email
$result->getUsername();     // string - Get username
$result->getFirstname();    // string - Get first name
$result->getLastname();     // string - Get last name
$result->getFullname();     // string - Get full name (or fallback to email/identifier)
$result->getType();         // string - Get connector type (e.g., "basic", "database")
$result->get($key);         // mixed - Get custom data
$result->toArray();         // array - Convert to array
```

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance86

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity83

Battle-tested with a long release history

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

Recently: every ~15 days

Total

11

Last Release

75d ago

Major Versions

1.2.0 → 2.0.02018-05-13

2.0.2 → 3.0.02025-12-04

PHP version history (5 changes)1.1.0PHP &gt;=5.6

2.0.0PHP ^7.1.3

3.0.0PHP ^8.0

3.5.0PHP ^8.1

3.6.4PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/5e83e3701566e43438525ed14578487e732b849d152b5071aa1613a0dad96913?d=identicon)[jdz](/maintainers/jdz)

---

Top Contributors

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

---

Tags

AuthenticationcoreJDZ

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jdz-authentication/health.svg)

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

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k50.9M364](/packages/tymon-jwt-auth)[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.7k143.0M272](/packages/league-oauth2-server)[league/oauth2-client

OAuth 2.0 Client Library

3.8k125.2M1.3k](/packages/league-oauth2-client)[google/auth

Google Auth Library for PHP

1.4k286.7M204](/packages/google-auth)[pragmarx/google2fa

A One Time Password Authentication package, compatible with Google Authenticator.

2.0k92.3M221](/packages/pragmarx-google2fa)[paragonie/sodium_compat

Pure PHP implementation of libsodium; uses the PHP extension if it exists

931141.1M172](/packages/paragonie-sodium-compat)

PHPackages © 2026

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