PHPackages                             hackthebox/laravel-iam-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. hackthebox/laravel-iam-auth

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

hackthebox/laravel-iam-auth
===========================

AWS IAM authentication for Laravel: RDS database connections and SDK credential caching for PHP-FPM

v2.0.2(1mo ago)4126[4 issues](https://github.com/hackthebox/laravel-iam-auth/issues)[1 PRs](https://github.com/hackthebox/laravel-iam-auth/pulls)MITPHPPHP ^8.2CI passing

Since Mar 6Pushed 1mo agoCompare

[ Source](https://github.com/hackthebox/laravel-iam-auth)[ Packagist](https://packagist.org/packages/hackthebox/laravel-iam-auth)[ RSS](/packages/hackthebox-laravel-iam-auth/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (7)Dependencies (16)Versions (19)Used By (0)

Laravel IAM Auth
================

[](#laravel-iam-auth)

AWS IAM authentication for Laravel: RDS database connections and SDK credential caching. Designed for EKS workloads using Pod Identity or IRSA — no sidecars, no static credentials.

Features
--------

[](#features)

- **RDS IAM Auth** — overrides Laravel's MySQL, MariaDB, and PostgreSQL connectors to generate short-lived IAM auth tokens via the AWS SDK when `use_iam_auth` is enabled on a connection.
- **AWS Credential Caching** — caches resolved AWS SDK credentials across PHP-FPM requests (APCu-first), benefiting all AWS SDK calls (S3, SQS, SES, etc.).

How It Works
------------

[](#how-it-works)

This package overrides Laravel's database connectors for MySQL, MariaDB, and PostgreSQL. When `use_iam_auth` is enabled on a connection, the connector generates a short-lived IAM auth token (via the AWS SDK) and uses it as the database password. Tokens are cached via APCu (preferred) or a configurable Laravel cache store to avoid per-request STS calls.

The package does **not** introduce a new database driver. Laravel's `MySqlConnection`, `MariaDbConnection`, and `PostgresConnection` are used as-is.

The package also extends the aws/aws-sdk-php-laravel SDK singleton to cache resolved AWS credentials across PHP-FPM requests, benefiting all AWS SDK calls in your application.

Driver Support
--------------

[](#driver-support)

Supports MySQL, MariaDB, and PostgreSQL. All three drivers share the same connector trait (`InjectsIamToken`), so the auth-token signing, cache-defense, and auth-rejection-detection behavior is identical across them.

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

[](#requirements)

- PHP &gt;= 8.2
- Laravel 11 or 12
- aws/aws-sdk-php-laravel &gt;= 3.7 and aws/aws-sdk-php &gt;= 3.249 (both installed automatically)
- APCu extension (recommended for production — caches tokens and credentials across FPM requests)
- RDS instance with IAM authentication enabled
- SSL CA bundle (bundled — override via `IAM_AUTH_SSL_CA_PATH` env if needed)

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

[](#installation)

```
composer require hackthebox/laravel-iam-auth
```

The service provider is auto-discovered. To publish the config:

```
php artisan vendor:publish --tag=iam-auth-config
```

Configuration
-------------

[](#configuration)

### Database Connection

[](#database-connection)

Add `use_iam_auth` and `region` to your connection in `config/database.php`:

**MySQL / MariaDB:**

```
'mysql' => [
    'driver' => 'mysql', // or 'mariadb'
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'use_iam_auth' => env('DB_USE_IAM_AUTH', false),
    'region' => env('AWS_DEFAULT_REGION', 'eu-central-1'),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],
```

**PostgreSQL:**

```
'pgsql' => [
    'driver' => 'pgsql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '5432'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'use_iam_auth' => env('DB_USE_IAM_AUTH', false),
    'region' => env('AWS_DEFAULT_REGION', 'eu-central-1'),
    'charset' => 'utf8',
    'prefix' => '',
    'schema' => 'public',
],
```

When `use_iam_auth` is `false`, the connector behaves identically to Laravel's default — `password` is used as-is.

### Environment Variables

[](#environment-variables)

**Production (EKS with Pod Identity):**

```
DB_USE_IAM_AUTH=true
DB_PASSWORD=
AWS_DEFAULT_REGION=eu-central-1
```

**Local development:**

```
DB_USE_IAM_AUTH=false
DB_PASSWORD=secret
```

### Package Config

[](#package-config)

The package config (`config/iam-auth.php`):

KeyDefaultDescription`region``AWS_DEFAULT_REGION` / `AWS_REGION` envFallback region when not set on connection`credential_provider``default`AWS credential provider for all SDK operations (S3, SQS, RDS, etc.). Override with `IAM_AUTH_CREDENTIAL_PROVIDER` env. Supported: `default`, `environment`, `ecs`, `web_identity`, `instance_profile`, `sso`, `ini`.`cache_store``null`Laravel cache store for caching RDS tokens and AWS credentials when APCu is unavailable. Use `file`, `redis`, `memcached`, etc. **Never** `database` or `dynamodb`. Override with `IAM_AUTH_CACHE_STORE` env.`cache_ttl``600` (10 min)RDS token cache TTL in seconds. Override with `IAM_AUTH_CACHE_TTL` env.`credentials_expiry_buffer``10` (seconds)Eviction buffer subtracted from AWS SDK credentials' reported expiration. Override with `IAM_AUTH_CREDENTIALS_EXPIRY_BUFFER` env. Negative or non-numeric values fall back to the default and log a boot-time warning.`debug``false`When `true`, emits verbose debug logging of credential and token cache state on every `getToken` call. High log volume; intended for short investigation soaks only. Override with `IAM_AUTH_DEBUG` env.`pgsql_sslmode``verify-full`SSL mode for PostgreSQL IAM connections. Override with `IAM_AUTH_PGSQL_SSLMODE` env.`ssl_ca_path`Bundled `global-bundle.pem`Path to the RDS CA bundle. Override with `IAM_AUTH_SSL_CA_PATH` env.RDS IAM Database User Setup
---------------------------

[](#rds-iam-database-user-setup)

### MySQL / MariaDB

[](#mysql--mariadb)

```
CREATE USER 'app_user' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';
GRANT ALL ON mydb.* TO 'app_user'@'%';
```

### PostgreSQL

[](#postgresql)

```
CREATE USER app_user WITH LOGIN;
GRANT rds_iam TO app_user;
```

EKS Pod Identity Setup
----------------------

[](#eks-pod-identity-setup)

1. Install the Pod Identity Agent addon
2. Create an IAM role with a trust policy for `pods.eks.amazonaws.com`
3. Attach an IAM policy allowing `rds-db:connect`
4. Create a pod identity association for your namespace/service account
5. Restart your pods

The AWS SDK default credential chain picks up Pod Identity credentials automatically. No code changes needed beyond enabling `use_iam_auth`.

*The option to force a specific credential provider exists via the `credential_provider` config option.*

Token Caching
-------------

[](#token-caching)

IAM auth tokens are valid for 15 minutes. The package caches them to avoid per-request STS calls:

1. **APCu** (highest priority) — shared memory, zero I/O. Best for PHP-FPM. Install `ext-apcu` and it's used automatically.
2. **Laravel cache store** — set `cache_store` to `file`, `redis`, `memcached`, etc. Good for queue workers or environments without APCu.
3. **No caching** — fresh token per connection. Fine for local dev (`use_iam_auth` is typically `false`) and short-lived CLI commands.

**Do not** set `cache_store` to `database` or `dynamodb` — this creates a circular dependency (need a DB connection to cache the token needed to open the DB connection). The package will throw a `RuntimeException` if you do.

**CLI and queue workers:** APCu is disabled in CLI by default (`apcu_enabled()` returns `false`). If you run queue workers with IAM auth, either set `apc.enable_cli=1` in your PHP CLI config, or configure a `cache_store` (e.g. `file` or `redis`).

**Cache security note:** When using `file`, `redis`, or `memcached` as the cache store, the IAM token is stored in plaintext. The token is short-lived (15 min) and scoped to a specific DB user, but ensure your cache backend is appropriately secured. APCu stores tokens in shared memory within the PHP process, which is not accessible externally.

**Bundled CA certificate:** The package includes the AWS RDS global CA bundle. This certificate bundle may become stale over time. If you encounter SSL verification errors, download the latest bundle from AWS and set `IAM_AUTH_SSL_CA_PATH` to point to it.

Defensive Behavior
------------------

[](#defensive-behavior)

The package guards against a failure mode where a cached IAM token would be reused with AWS credentials whose underlying STS session has rotated (or evicted from the credential cache) since the token was signed. RDS would otherwise accept the SigV4 signature but reject the now-stale session token, surfacing as `Access denied for user '...' (using password: YES)`.

- **Expired-on-arrival credentials throw.** When the AWS SDK credential provider hands back a `Credentials` object that is already past its expiration, `AwsCredentialCache::resolve()` throws a `RuntimeException` instead of passing them to the SigV4 signer, and emits a `Log::warning` under the channel `iam-auth.credentials-expired-on-arrival` for operator visibility. Callers should retry after a short backoff rather than catching and ignoring.
- **Cached RDS tokens carry a signing-credentials fingerprint.** Each cached entry is `{ token, sig_kid, signed_at }`, where `sig_kid` is a truncated SHA-256 of the `AccessKeyId + SecurityToken` that signed the token. On retrieval, the package compares the entry's `sig_kid` against the current credentials' fingerprint; on mismatch (or any non-conforming legacy entry), the token is regenerated and re-cached. APCu cache-miss atomicity (`apcu_entry`) is preserved.

Both guards are always on and agnostic to session-duration and agent-refresh-cadence configuration. No credential secrets are logged or persisted; only the truncated `sig_kid` and a `signed_at` timestamp accompany the token in the cache.

**Performance note.** Computing the current fingerprint requires resolving credentials on every `getToken()` call, even on a token-cache hit. The cost is dominated by `AwsCredentialCache::resolve()`, which is APCu-backed in production and effectively free. If you disable credential caching (no APCu, no `cache_store`), every DB connection will re-invoke the SDK credential chain — keep credential caching enabled for IAM-auth workloads.

**Concurrency note.** On a `sig_kid` mismatch the package re-signs and overwrites the cache entry. Under concurrent workers this overwrite is not serialized (only the initial `apcu_entry` cache-miss is atomic). During a credential rotation window, N workers may each detect mismatch and redundantly re-sign. SigV4 signing is local HMAC work and all workers produce equivalent tokens, so the result is correct; the cost is bounded by the rotation frequency and is negligible in practice.

Any auth rejection from RDS that reaches the connector (SQLSTATE class `28` for PostgreSQL, native code `1045` for MySQL/MariaDB) is logged at `warning` level under the structured channel `iam-auth.rds-auth-rejected`, carrying the cached credential state at the moment of rejection. Useful as an operational signal for monitoring or alerting on auth failures.

The credential snapshot reflects the cache state **at the moment the warning fires**, not the exact credentials used to sign the rejected token. In practice these are the same (the window between signing and rejection is small and the credentials cache rarely rotates within it), but on a busy multi-worker pod a concurrent refresh between signing and rejection can produce a snapshot of post-rotation credentials.

Operators who observe clock drift or want more aggressive credential refresh (e.g. for CI smoke tests against rotating credentials) can tune `IAM_AUTH_CREDENTIALS_EXPIRY_BUFFER` (default `10` seconds). Negative or non-numeric values fall back to the default and emit a boot-time warning.

Debugging
---------

[](#debugging)

Set `IAM_AUTH_DEBUG=true` in your environment to enable verbose per-`getToken` logging. The package emits an `iam-auth.token-access` debug line on every call with the credential and token cache state at that moment:

- `current_sig_kid` — fingerprint of the credentials about to sign the token.
- `cached_sig_kid` — fingerprint stored in the cached entry (if any).
- `sig_kid_match` — whether the cached entry matches the current credentials.
- `cred_is_expired`, `cred_expires_in_s` — client-side credential lifetime.
- `cred_access_key_prefix` — first 8 characters of the AccessKeyId (never the full credential).

The `iam-auth.rds-auth-rejected` warning is unconditional and fires regardless of `IAM_AUTH_DEBUG`; it carries the same credential snapshot.

This log volume is too high for steady-state production. Enable for short investigation soaks only. No credential secrets are ever logged.

Note: under `IAM_AUTH_DEBUG=true` each `getToken()` performs two cache reads — one to assemble the debug snapshot and one for the actual lookup. Negligible at investigation cadence; another reason not to leave debug on in steady state.

AWS Credential Caching
----------------------

[](#aws-credential-caching)

When using IAM roles (IRSA, Pod Identity, instance profiles), the AWS SDK resolves credentials via network calls to STS or IMDS on every PHP-FPM request. Under high traffic this adds latency and can hit rate limits.

This package caches resolved AWS SDK credentials across requests, benefiting **all** AWS SDK calls made by your application (S3, SQS, SES, etc.), not just RDS token generation.

The same `cache_store` setting controls both RDS token caching and AWS credential caching (with separate cache keys and TTLs). APCu is always preferred when available.

**Important:** Credential caching only applies to AWS clients created through the SDK singleton (e.g. `app('aws')->createS3()`). Clients instantiated directly (`new S3Client([...])`) bypass the singleton and do not benefit from cached credentials. Always resolve clients via the container:

```
// Correct: uses cached credentials
$s3 = app('aws')->createS3();

// Bypasses credential caching
$s3 = new \Aws\S3\S3Client([...]);
```

**Cache security note:** Cached credentials are stored in plaintext in the configured backend. Ensure your cache backend is appropriately secured. APCu stores credentials in shared memory within the PHP process, which is not accessible externally.

**Static credentials are not cached.** Credentials without a reported expiration (e.g. static env keys, `~/.aws/credentials` profiles without an `expiration`) cannot be safely cached because the package has no signal for when to evict them. Each request will re-invoke the SDK credential chain. This is intentional: stale long-lived credentials would otherwise outlive their server-side validity and trigger the very failure mode the cache fingerprint guards against. Production workloads on IRSA / Pod Identity / instance profiles get full caching benefits because the SDK reports an expiration.

License
-------

[](#license)

MIT

###  Health Score

42

—

FairBetter than 89% of packages

Maintenance73

Regular maintenance activity

Popularity18

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95.8% 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 ~5 days

Total

16

Last Release

36d ago

Major Versions

v1.1.0 → v2.0.02026-03-26

v2.0.1 → v3.0.0-rc.12026-05-19

v2.0.2 → v3.0.0-rc.82026-05-21

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8687447?v=4)[makelarisjr](/maintainers/makelarisjr)[@makelarisjr](https://github.com/makelarisjr)

![](https://avatars.githubusercontent.com/u/13113025?v=4)[Dimosthenis Schizas](/maintainers/dimoschi)[@dimoschi](https://github.com/dimoschi)

---

Top Contributors

[![dimoschi](https://avatars.githubusercontent.com/u/13113025?v=4)](https://github.com/dimoschi "dimoschi (69 commits)")[![vlasopoulos](https://avatars.githubusercontent.com/u/1096466?v=4)](https://github.com/vlasopoulos "vlasopoulos (3 commits)")

---

Tags

laravelawsAuthenticationiamrdsekspod-identitycredential-caching

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/hackthebox-laravel-iam-auth/health.svg)

```
[![Health](https://phpackages.com/badges/hackthebox-laravel-iam-auth/health.svg)](https://phpackages.com/packages/hackthebox-laravel-iam-auth)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[laravel/ai

The official AI SDK for Laravel.

9782.1M162](/packages/laravel-ai)[ellaisys/aws-cognito

AWS Cognito package that allows Auth and other related features using the AWS SDK for PHP

121242.9k1](/packages/ellaisys-aws-cognito)[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6753.6k5](/packages/hasinhayder-tyro)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45344.0k1](/packages/pressbooks-pressbooks)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2013.2k](/packages/alajusticia-laravel-logins)

PHPackages © 2026

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