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

Crayfish Commons Syn Laravel Package

discoverygarden/crayfish-commons-syn

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require discoverygarden/crayfish-commons-syn
    

    Ensure your project meets the PHP 7.2+ requirement.

  2. Configure security.yaml: Add the package to your config/packages/security.yaml (or equivalent):

    security:
      enable_authenticator_manager: true
      providers:
        users_in_memory:
          memory: ~
      firewalls:
        main:
          anonymous: false
          provider: users_in_memory
          custom_authenticators:
            - islandora_crayfish_commons_syn.jwt.authenticator
    
  3. First Use Case: Test JWT authentication by sending a request with a valid Authorization: Bearer <token> header. Verify the response includes the expected authenticated user data.


Implementation Patterns

Core Workflows

  1. Multi-Tenancy Integration:

    • Use the package to handle JWT validation for tenant-specific tokens in a shared authentication layer.
    • Extend the islandora_crayfish_commons_syn.jwt.authenticator to include tenant ID in token claims (e.g., tenant_id).
    • Example token payload:
      {
        "sub": "user@example.com",
        "tenant_id": "tenant_123",
        "exp": 1234567890
      }
      
  2. Custom Auth Logic:

    • Override the authenticator service to add pre/post-validation logic:
      // services.yaml
      islandora_crayfish_commons_syn.jwt.authenticator:
        class: App\Security\CustomSynAuthenticator
        arguments: ['@islandora_crayfish_commons_syn.jwt.authenticator']
      
      // src/Security/CustomSynAuthenticator.php
      class CustomSynAuthenticator extends AbstractAuthenticator {
          public function supports(Request $request) {
              // Add tenant-specific checks
              return parent::supports($request);
          }
      }
      
  3. Token Generation:

    • Use LexikJWT’s JWTManagerInterface to generate tokens with tenant context:
      $token = $jwtManager->create([
          'sub' => $user->getEmail(),
          'tenant_id' => $tenant->getId(),
      ]);
      
  4. API Integration:

    • Secure API endpoints with the main firewall. Example controller:
      #[Route('/api/protected', methods: ['GET'])]
      public function protectedRoute(UserInterface $user, TenantManager $tenantManager) {
          $tenant = $tenantManager->findById($user->getTenantId());
          return new JsonResponse(['tenant' => $tenant->getName()]);
      }
      

Gotchas and Tips

Pitfalls

  1. Missing Provider Configuration:

    • Forgetting to define a provider under security.firewalls.main will cause silent authentication failures.
    • Fix: Ensure provider: users_in_memory (or your custom provider) is set.
  2. Token Claims Mismatch:

    • If the token lacks expected claims (e.g., tenant_id), the authenticator may reject it.
    • Fix: Validate claims in a custom authenticator or adjust token generation.
  3. Caching Issues:

    • LexikJWT’s token storage (e.g., Redis) may cause stale tokens if not flushed.
    • Fix: Clear cache after token revocation:
      php bin/console lexik_jwt:purge
      
  4. Firewall Order:

    • Placing the main firewall after another firewall (e.g., dev) may bypass the JWT check.
    • Fix: Ensure main is listed first in security.firewalls.

Debugging Tips

  • Enable Debug Mode:

    # config/packages/security.yaml
    security:
      debug: true
    

    Logs authentication events to var/log/dev.log.

  • Token Validation: Use LexikJWT’s debug command to validate tokens:

    php bin/console lexik_jwt:debug-token <your_token_here>
    
  • Event Listeners: Subscribe to security.authentication.success to log tenant-specific events:

    // src/EventListener/AuthListener.php
    class AuthListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                SecurityEvents::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess',
            ];
        }
        public function onAuthenticationSuccess(AuthenticationSuccessEvent $event) {
            $user = $event->getUser();
            $tenantId = $user->getTenantId();
            // Log or process tenant-specific logic
        }
    }
    

Extension Points

  1. Custom Token Claims: Extend the authenticator to support additional claims (e.g., roles, permissions):

    // src/Security/CustomAuthenticator.php
    public function getCredentials(Request $request) {
        $token = $this->jwtManager->getUserByToken($request->headers->get('Authorization'));
        return [
            'username' => $token['sub'],
            'tenant_id' => $token['tenant_id'] ?? null,
            'roles' => $token['roles'] ?? [],
        ];
    }
    
  2. Tenant-Aware User Providers: Override the user provider to fetch users based on tenant context:

    // src/Security/TenantUserProvider.php
    class TenantUserProvider implements UserProviderInterface {
        public function loadUserByUsername($username) {
            $tenantId = $this->requestStack->getCurrentRequest()->attributes->get('tenant_id');
            // Fetch user with tenant context
        }
    }
    
  3. Token Refresh: Implement a custom refresh token endpoint using LexikJWT’s RefreshTokenManagerInterface:

    #[Route('/api/token/refresh', methods: ['POST'])]
    public function refreshToken(RefreshTokenManagerInterface $refreshTokenManager) {
        $refreshToken = $this->request->request->get('refresh_token');
        $newToken = $refreshTokenManager->refresh($refreshToken);
        return new JsonResponse(['token' => $newToken]);
    }
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony