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

nette/security

Nette Security provides authentication and authorization for PHP apps, with ready-to-use user identity, login/logout handling, roles and permissions, and easy integration with Nette Framework services for secure access control.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation:

    composer require nette/security
    

    Note: Requires PHP 8.1+. Use nette/utils as a dependency if not already present.

  2. Basic Configuration (via Laravel Service Provider):

    use Nette\Security\SecurityExtension;
    use Nette\DI\Container;
    
    public function register()
    {
        $this->container->addService('security', function (Container $container) {
            $security = new SecurityExtension();
            $security->setup($container);
            return $security;
        });
    }
    
  3. First Use Case: User Authentication

    use Nette\Security\User;
    use Nette\Security\Identity;
    
    // In a controller/middleware
    $user = app('security.user');
    if ($user->isLoggedIn()) {
        $identity = $user->getIdentity();
        // $identity is an Identity object with roles/data
    }
    
  4. Quick Login Flow:

    $authenticator = app('security.authenticator');
    $authenticator->authenticate([
        'username' => 'admin',
        'password' => 'secure123'
    ]);
    

Implementation Patterns

Core Workflows

1. Authentication Flow

  • Login:

    $authenticator = app('security.authenticator');
    $authenticator->authenticate([
        'username' => $request->input('username'),
        'password' => $request->input('password')
    ]);
    

    Tip: Use SimpleAuthenticator for basic setups (supports dynamic passwords via $userData).

  • Logout:

    $user = app('security.user');
    $user->logout(true); // true = clear identity immediately
    

2. Role-Based Authorization

  • Check Roles:
    if ($user->isAllowed('admin', 'dashboard')) {
        // Grant access
    }
    
    Pattern: Use Authorizator for resource-level permissions:
    $authorizator = app('security.authorizator');
    if ($authorizator->isAllowed($user->getIdentity(), 'resource:post', 'edit')) {
        // Allow edit
    }
    

3. Custom Identity Handling

  • Guest Identity (v3.2.4+):
    $identityHandler = app('security.identityHandler');
    $guestIdentity = $identityHandler->getGuestIdentity(); // Returns ?Identity
    
    Use Case: Assign guest roles (e.g., ['guest']) without hitting storage.

4. Session Management

  • Sliding Expiration (v3.2.3+):
    $storage = app('security.sessionStorage');
    $storage->setExpiration(new \DateTime('+1 hour')); // No silent revalidation
    
    Tip: Use User::setExpiration() for user-specific timeouts:
    $user->setExpiration(new \DateTime('+30 minutes'), true);
    

Integration Tips

Laravel-Specific Adaptations

  1. Middleware Integration:

    namespace App\Http\Middleware;
    use Nette\Security\User;
    
    class Authenticate
    {
        public function handle($request, Closure $next, User $user)
        {
            if (!$user->isLoggedIn()) {
                return redirect()->route('login');
            }
            return $next($request);
        }
    }
    
  2. Service Provider Binding:

    public function boot()
    {
        $this->app->singleton('security.user', function ($app) {
            return new User(
                $app['security.authenticator'],
                $app['security.authorizator'],
                $app['security.sessionStorage']
            );
        });
    }
    
  3. Password Hashing:

    $passwords = app('security.passwords');
    $hash = $passwords->hash('plaintext', 'bcrypt', ['cost' => 12]);
    $isValid = $passwords->verify('plaintext', $hash);
    

Testing Patterns

  • Mock Authenticator:

    $mockAuthenticator = $this->createMock(Authenticator::class);
    $mockAuthenticator->method('authenticate')->willReturn(new Identity('user1', ['user']));
    $this->app->instance('security.authenticator', $mockAuthenticator);
    
  • Assert Roles:

    $this->assertTrue($user->isInRole('admin'));
    $this->assertFalse($user->isInRole('guest'));
    

Gotchas and Tips

Pitfalls

  1. Session Storage Quirks:

    • Expired Sessions: v3.2.3+ fixes silent revalidation, but ensure your Laravel session driver (e.g., Redis) respects the expiration.
    • CookieStorage: Requires SameSite attribute setup. Use:
      $storage = new CookieStorage('auth', [
          'httponly' => true,
          'secure' => env('APP_ENV') === 'production',
          'samesite' => 'Lax',
      ]);
      
  2. BC Breaks:

    • v3.2.0+: IUserStorage is removed. Migrate to UserStorage.
    • v3.1.0+: IAuthorizatorAuthorizator (no I prefix).
  3. Guest Identity:

    • Only falls back to getGuestIdentity() if isLoggedIn() is false. Override IdentityHandler to customize:
      class CustomIdentityHandler implements IdentityHandler
      {
          public function getGuestIdentity(): ?Identity
          {
              return new Identity('guest', ['guest'], ['name' => 'Anonymous']);
          }
      }
      
  4. Password Hashing:

    • Default Algorithm: BCRYPT (v3.0.1+). Avoid hardcoding salts.
    • Empty Passwords: Passwords::hash() throws on empty input (v3.0.5+).

Debugging Tips

  1. Identity Cache:

    • Clear with $user->refreshStorage() if roles/data appear stale.
  2. Authorization Debugging:

    • Enable Tracy (if using Nette) or log Authorizator decisions:
      $authorizator->onDenied[] = function ($resource, $role, $privilege) {
          \Log::debug("Access denied: {$resource} for {$role}");
      };
      
  3. Session Issues:

    • Check SessionStorage::getState() for null (expired) vs. Identity objects.
    • Use UserPanel for debugging (requires Tracy):
      $userPanel = new UserPanel($user);
      echo $userPanel->render();
      

Extension Points

  1. Custom Authenticators:

    class DatabaseAuthenticator implements Authenticator
    {
        public function authenticate(array $credentials): ?Identity
        {
            $user = User::where('email', $credentials['username'])->first();
            if ($user && $this->passwords->verify($credentials['password'], $user->password)) {
                return new Identity($user->id, ['user', ...$user->roles]);
            }
            return null;
        }
    }
    
  2. Dynamic Roles:

    • Extend Identity to fetch roles from a database:
      class DynamicIdentity extends SimpleIdentity
      {
          public function getRoles(): array
          {
              return $this->roles ?? $this->loadRolesFromDb($this->id);
          }
      }
      
  3. Event Listeners:

    • Hook into User::onLogin/onLogout:
      $user->onLogin[] = function ($identity) {
          \Log::info("User {$identity->id} logged in");
      };
      

Laravel-Specific Quirks

  1. Session Driver Conflicts:

    • If using database or redis sessions, ensure SessionStorage is initialized after Laravel’s session starts:
      $storage = new SessionStorage($session->getHandler());
      
  2. CSRF Integration:

    • nette/security does not handle CSRF. Use Laravel’s built-in middleware alongside:
      $middleware->append(\App\Http\Middleware\EncryptCookies::class);
      $middleware->append(\Illuminate\Session\Middleware\StartSession::class);
      
  3. Password Reset:

    • Combine with Laravel’s Password::reset() and use nette/security for hashing:
      $newHash = app('security.passwords')->hash($request->password);
      User::where('email', $email)->update(['password' => $newHash]);
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle