Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravault Auth Laravel Package

codybuell/laravault-auth

Laravel 5.4 auth provider that authenticates users against Hashicorp Vault. Stores user info in the Laravel session, tracks Vault TTL, and ends the Laravel session when the Vault token expires. Configurable as an auth driver via config/auth.php.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require codybuell/laravault-auth
    

    Publish the config file:

    php artisan vendor:publish --provider="CodyBuell\LaravaultAuth\LaravaultAuthServiceProvider" --tag="config"
    
  2. Configure Vault Connection Edit config/laravault-auth.php with your Vault server URL, token, or auth method (e.g., AppRole, AWS IAM, or Kubernetes auth):

    'vault' => [
        'url' => env('VAULT_ADDR', 'https://vault.example.com'),
        'token' => env('VAULT_TOKEN'),
        // OR use auth method (e.g., 'approle', 'aws', 'kubernetes')
        'auth' => [
            'method' => 'approle',
            'role_id' => env('VAULT_APPROLE_ROLE_ID'),
            'secret_id' => env('VAULT_APPROLE_SECRET_ID'),
        ],
    ],
    
  3. First Use Case: Fetch a Secret Retrieve a secret from Vault (e.g., database credentials):

    use CodyBuell\LaravaultAuth\Facades\LaravaultAuth;
    
    $dbConfig = LaravaultAuth::get('secret/data/db/config');
    // Returns decrypted data (e.g., ['username' => '...', 'password' => '...'])
    

Implementation Patterns

1. Authenticating with Vault

  • Dynamic Token Rotation: Use the refreshToken() method to rotate tokens periodically (e.g., in a scheduled job):
    LaravaultAuth::refreshToken(); // Updates the current token via auth method
    
  • Auth Method Flexibility: Swap between token, approle, aws, or kubernetes in config without code changes.

2. Reading Secrets

  • Path-Based Access: Fetch secrets by path (supports KV v1/v2):
    $secret = LaravaultAuth::get('secret/data/app/config');
    
  • Versioned Secrets: Use getVersioned() to retrieve a specific version:
    $secret = LaravaultAuth::getVersioned('secret/data/app/config', '1');
    
  • List Secrets: Enumerate keys in a path:
    $keys = LaravaultAuth::list('secret/data/app/');
    

3. Writing Secrets

  • Store Secrets: Write to Vault (requires write capability):
    LaravaultAuth::set('secret/data/app/config', ['key' => 'value']);
    
  • Delete Secrets: Remove entries:
    LaravaultAuth::delete('secret/data/app/config');
    

4. Integration with Laravel

  • Service Provider Binding: Bind Vault secrets to Laravel’s container:
    $this->app->bind('vault.db', function () {
        return LaravaultAuth::get('secret/data/db/config');
    });
    
  • Environment Variables: Dynamically load Vault secrets into .env (use laravel/env-vault or custom logic):
    $envVars = LaravaultAuth::get('secret/data/env');
    putenv("DB_PASSWORD={$envVars['password']}");
    

5. Error Handling

  • Graceful Fallbacks: Use try-catch for Vault failures:
    try {
        $secret = LaravaultAuth::get('secret/data/nonexistent');
    } catch (\CodyBuell\LaravaultAuth\Exceptions\VaultException $e) {
        log::error("Vault fetch failed: " . $e->getMessage());
        // Fallback to local config
    }
    

Gotchas and Tips

Pitfalls

  1. Token Expiry: Vault tokens expire. Always use refreshToken() in long-running processes or implement a middleware to refresh tokens on demand.
    // Middleware example:
    public function handle($request, Closure $next) {
        LaravaultAuth::refreshToken();
        return $next($request);
    }
    
  2. Permission Denied: Ensure the Vault token/auth method has the correct policies (e.g., read/write on paths).
  3. Path Format: KV v2 requires /data/ in paths (e.g., secret/data/app/config), while v1 omits it. Double-check your Vault setup.
  4. Network Issues: Vault may time out. Implement retries with exponential backoff:
    use Illuminate\Support\Facades\Retry;
    
    Retry::retry(3, function () {
        LaravaultAuth::get('secret/data/app/config');
    });
    

Debugging Tips

  • Enable Debugging: Set debug to true in config to log raw Vault responses:
    'debug' => env('VAULT_DEBUG', false),
    
  • Check HTTP Status: Vault returns 404 for missing secrets and 403 for permission issues. Log the full response for debugging:
    try {
        LaravaultAuth::get('secret/data/app/config');
    } catch (\CodyBuell\LaravaultAuth\Exceptions\VaultException $e) {
        \Log::debug($e->getResponse()->getBody());
    }
    

Extension Points

  1. Custom Auth Methods: Extend the AuthMethod interface to support additional auth backends (e.g., LDAP, JWT).
  2. Secret Transformation: Chain a transform() method to decrypt or modify secrets before use:
    $secret = LaravaultAuth::get('secret/data/app/config')->transform(function ($data) {
        return base64_decode($data['encrypted_value']);
    });
    
  3. Caching: Cache frequently accessed secrets in Laravel’s cache or Redis:
    $cacheKey = 'vault:db:config';
    $dbConfig = cache()->remember($cacheKey, now()->addHours(1), function () {
        return LaravaultAuth::get('secret/data/db/config');
    });
    
  4. Event Listeners: Trigger events when secrets are read/written (e.g., audit logging):
    LaravaultAuth::listen('secret.read', function ($path, $data) {
        \Log::info("Secret read from $path", $data);
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log