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

Security utilities for Nette apps: authentication and authorization helpers, user identity and roles, access control checks, and related infrastructure for building secure login flows and protecting resources with a consistent API.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the Package

    composer require nette/security
    

    Note: Since this is Nette-focused, you’ll need to manually integrate it with Laravel’s DI container.

  2. Configure Basic Authentication Add to config/services.php:

    'security' => [
        'authentication' => [
            'storage' => \Nette\Security\SessionStorage::class,
            'persistIdentity' => true, // Default: true
        ],
        'roles' => ['admin', 'editor', 'user'],
        'resources' => ['dashboard', 'profile', 'settings'],
    ],
    
  3. Create a Simple Authenticator

    use Nette\Security\Authenticator;
    use Nette\Security\Identity;
    
    class UserAuthenticator implements Authenticator
    {
        public function authenticate(array $credentials): Identity
        {
            $user = User::where('email', $credentials['email'])->first();
            if (!$user || !password_verify($credentials['password'], $user->password)) {
                throw new \Nette\Security\AuthenticationException('Invalid credentials.');
            }
            return new \Nette\Security\SimpleIdentity($user->id, $user->roles);
        }
    }
    
  4. Register Services in AppServiceProvider

    public function register()
    {
        $this->app->singleton(\Nette\Security\User::class, function ($app) {
            $authenticator = new UserAuthenticator();
            $storage = new \Nette\Security\SessionStorage($app['session.store']);
            return new \Nette\Security\User($authenticator, $storage);
        });
    }
    
  5. First Use Case: Protect a Route

    Route::get('/dashboard', function () {
        $user = app(\Nette\Security\User::class);
        if (!$user->isLoggedIn()) {
            abort(403);
        }
        return view('dashboard');
    })->middleware('auth');
    

Implementation Patterns

Core Workflows

1. Authentication Flow

  • Login:
    $user = app(\Nette\Security\User::class);
    $user->login($credentials, $authenticator);
    
  • Logout:
    $user->logout($clearIdentity = true); // Default: true
    
  • Guest Identity (v3.2.4+):
    $user->getGuestIdentity(); // Returns a SimpleIdentity for anonymous users
    

2. Authorization Patterns

  • Role-Based Checks:
    if ($user->isInRole('admin')) {
        // Admin-only logic
    }
    
  • Resource Permissions:
    $authorizator = $user->getAuthorizator();
    if ($authorizator->isAllowed('admin', 'dashboard', 'view')) {
        // Grant access
    }
    
  • Dynamic Permissions:
    $authorizator->addPermission('admin', 'dashboard', 'edit', function ($user) {
        return $user->isInRole('superadmin');
    });
    

3. Session Management

  • Sliding Expiration:
    $storage = $user->getStorage();
    $storage->setExpiration(new \DateTime('+1 hour'));
    
  • Manual Expiration:
    $user->setExpiration(new \DateTime('+30 minutes'), true); // Clear identity
    

4. Password Handling

  • Hashing:
    $passwords = app(\Nette\Security\Passwords::class);
    $hash = $passwords->hash('plaintext');
    
  • Verification:
    if ($passwords->verify('plaintext', $hash)) {
        // Valid
    }
    

Integration Tips

Laravel-Specific Adaptations

  1. Middleware for Authentication:

    class NetteAuthMiddleware
    {
        public function handle($request, Closure $next)
        {
            $user = app(\Nette\Security\User::class);
            if (!$user->isLoggedIn()) {
                return redirect()->route('login');
            }
            return $next($request);
        }
    }
    
  2. Leverage Laravel’s Session:

    $storage = new \Nette\Security\SessionStorage($request->getSession());
    
  3. Custom Identity Storage:

    class DatabaseStorage implements \Nette\Security\UserStorage
    {
        public function getIdentity($id)
        {
            return User::find($id)?->toIdentity();
        }
        // ... other methods
    }
    

Common Extensions

  1. Event Listeners:

    $user->onAuthenticate[] = function ($user, $authenticator) {
        // Post-auth logic (e.g., log activity)
    };
    
  2. Dynamic Role Assignment:

    $user->getRoles(); // Returns array|string
    $user->setRoles(['admin', 'editor']); // Update roles
    
  3. Guest Role Fallback:

    $user->getRoles(); // Returns ['guest'] if not logged in
    

Gotchas and Tips

Pitfalls

  1. Session Storage Assumptions:

    • The package defaults to session-based storage, which may conflict with Laravel’s session drivers (e.g., Redis, database). Use CookieStorage for stateless setups:
      $storage = new \Nette\Security\CookieStorage($request, 'auth_token');
      
  2. Identity Persistence:

    • persistIdentity (v3.2.4+) defaults to true, meaning identities linger after logout for personalization (e.g., "Welcome back, John"). Set to false to fully clear:
      'authentication' => [
          'persistIdentity' => false,
      ]
      
  3. Guest Identity Quirks:

    • Guest identities are read-only and never persisted. Override getGuestIdentity() in a custom IdentityHandler:
      class CustomIdentityHandler implements \Nette\Security\IdentityHandler
      {
          public function getGuestIdentity(): ?\Nette\Security\IIdentity
          {
              return new \Nette\Security\SimpleIdentity('guest', ['guest']);
          }
      }
      
  4. BC Breaks in v3.x:

    • IUserStorage was removed in v3.1.0. Migrate to UserStorage:
      // Old (v2.x)
      $storage = new \Nette\Http\UserStorage();
      
      // New (v3.x)
      $storage = new \Nette\Security\SessionStorage($session);
      
  5. Password Hashing:

    • Defaults to bcrypt (v3.0.1+). For custom algorithms, configure:
      $passwords = new \Nette\Security\Passwords();
      $passwords->setAlgorithm(\Nette\Security\Passwords::PASSWORD_ARGON2I);
      

Debugging Tips

  1. Check Identity State:

    var_dump($user->isLoggedIn(), $user->getIdentity(), $user->getRoles());
    
  2. Inspect Storage:

    $storage = $user->getStorage();
    $storage->getState(); // Returns session/cookie data
    
  3. Enable Tracy (Nette Debugger):

    $user->getAuthenticator()->onAuthenticate[] = function ($user, $authenticator) {
        \Tracy\Debugger::barDump($user->getIdentity());
    };
    
  4. Log Exceptions:

    try {
        $user->login($credentials, $authenticator);
    } catch (\Nette\Security\AuthenticationException $e) {
        \Log::error('Auth failed: ' . $e->getMessage());
    }
    

Extension Points

  1. Custom Authenticators:

    class ApiAuthenticator implements \Nette\Security\Authenticator
    {
        public function authenticate(array $credentials): \Nette\Security\Identity
        {
            // API token validation logic
            return new \Nette\Security\SimpleIdentity($userId, ['api_user']);
        }
    }
    
  2. Dynamic Authorizators:

    $authorizator = new \Nette\Security\Authorizator();
    $authorizator->addResource('admin', [
        'dashboard' => ['view', 'edit'],
        'users' => ['list', 'create'],
    ]);
    
  3. Override Storage:

    class DatabaseUserStorage implements \Nette\Security\UserStorage
    {
        public function getIdentity($id)
        {
            return User::find($id)?->toIdentity();
        }
        public function saveIdentity(\Nette\Security\Identity $identity)
    
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony