Weave Code
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

Security Laravel Package

draw/security

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require draw/security
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Draw\Security\SecurityServiceProvider::class,
    ],
    
  2. Basic Usage The package provides a Security facade for common security operations. Import it in your controller or service:

    use Draw\Security\Facades\Security;
    
  3. First Use Case: Password Hashing Hash a password (compatible with Symfony’s PasswordHasher):

    $hashedPassword = Security::hashPassword('plain-text-password');
    
  4. First Use Case: Password Verification Verify a password against a hash:

    $isValid = Security::verifyPassword('plain-text-password', $hashedPassword);
    
  5. Configuration Check config/security.php for default settings (e.g., hashing algorithm, cost factors). Override as needed:

    'hashing' => [
        'algorithm' => 'bcrypt',
        'cost' => 12,
    ],
    

Implementation Patterns

Core Workflows

  1. Authentication Use the Authenticator class to handle login/logout flows:

    // Login
    $user = Security::authenticate($credentials);
    Security::login($user);
    
    // Logout
    Security::logout();
    
  2. Role-Based Access Control (RBAC) Define roles in config/security.php:

    'roles' => [
        'admin' => ['create', 'read', 'update', 'delete'],
        'user' => ['read'],
    ],
    

    Check permissions in controllers:

    if (Security::isGranted('ROLE_ADMIN', 'create')) {
        // Allow action
    }
    
  3. CSRF Protection Generate and validate tokens in forms:

    // Generate token
    $token = Security::generateCsrfToken();
    
    // Validate token
    if (Security::validateCsrfToken($token)) {
        // Proceed
    }
    
  4. Password Reset Use the PasswordReset helper for secure token generation and validation:

    $token = Security::generatePasswordResetToken($user->email);
    $isValid = Security::validatePasswordResetToken($token);
    

Integration Tips

  • Laravel Auth Integration Extend Laravel’s Authenticatable to use the Security facade for password hashing:

    use Draw\Security\Facades\Security;
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    
    class User extends Authenticatable implements MustVerifyEmail
    {
        public function setPasswordAttribute($password)
        {
            $this->attributes['password'] = Security::hashPassword($password);
        }
    }
    
  • Middleware Create custom middleware for role checks:

    namespace App\Http\Middleware;
    
    use Draw\Security\Facades\Security;
    use Closure;
    
    class RoleMiddleware
    {
        public function handle($request, Closure $next, $role)
        {
            if (!Security::isGranted($role)) {
                abort(403);
            }
            return $next($request);
        }
    }
    
  • Event Listeners Listen for security events (e.g., auth.attempted, password.reset) via Laravel’s event system:

    Security::addListener('auth.attempted', function ($event) {
        // Log failed attempts
    });
    

Gotchas and Tips

Pitfalls

  1. Algorithm Compatibility

    • The package defaults to bcrypt, but Symfony’s PasswordHasher supports multiple algorithms (e.g., argon2i). Ensure your Laravel app’s App\Providers\AppServiceProvider configures the hasher correctly:
      use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher;
      use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory;
      
      public function register()
      {
          $this->app->singleton(UserPasswordHasher::class, function ($app) {
              return new UserPasswordHasher(
                  new PasswordHasherFactory(),
                  'bcrypt', // or 'argon2i'
                  ['cost' => 12]
              );
          });
      }
      
  2. Token Storage

    • CSRF tokens and password reset tokens are not persisted by default. Store them in the session or database manually:
      session(['csrf_token' => Security::generateCsrfToken()]);
      
  3. Role Hierarchy

    • The package does not enforce role hierarchy (e.g., admin > user). Implement this logic in your isGranted checks:
      if (Security::isGranted('ROLE_ADMIN') || Security::isGranted('ROLE_USER')) {
          // Allow
      }
      
  4. Deprecation Risks

    • The package is unmaintained (0 stars, no dependents). Test thoroughly and consider forking if critical for your project.

Debugging

  • Password Hashing Issues

    • Verify the algorithm and cost in config/security.php match your expectations. Use Symfony’s PasswordHasher directly for debugging:
      $hasher = app(UserPasswordHasher::class);
      $hash = $hasher->hashPassword($user, 'plain-password');
      
  • CSRF Token Mismatches

    • Ensure tokens are generated and validated in the same request lifecycle. Use middleware to enforce CSRF checks globally:
      // app/Http/Middleware/VerifyCsrfToken.php
      public function handle($request, Closure $next)
      {
          if (!Security::validateCsrfToken($request->input('_token'))) {
              abort(403);
          }
          return $next($request);
      }
      

Extension Points

  1. Custom Hashers

    • Extend the Security facade to support additional hashing algorithms:
      Security::extendHasher('argon2id', function () {
          return new Argon2idHasher();
      });
      
  2. Event System

    • Add custom events for security actions:
      Security::addListener('auth.failed', function ($event) {
          // Trigger analytics
      });
      
  3. Database Backend

    • Replace in-memory token storage with a database-backed solution by extending the TokenManager class:
      class DatabaseTokenManager extends TokenManager
      {
          public function generateToken()
          {
              $token = parent::generateToken();
              DB::table('tokens')->insert(['token' => $token]);
              return $token;
          }
      }
      
  4. Two-Factor Authentication (2FA)

    • Integrate with Laravel’s two-factor package or build custom 2FA logic using the Security facade’s event system.
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle