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

Auth Bundle Laravel Package

appshed/auth-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to composer.json:

    composer require appshed/auth-bundle
    

    Register in config/bundles.php (Symfony 3/4/5):

    return [
        // ...
        AppShed\AuthBundle\AppShedAuthBundle::class => ['all' => true],
    ];
    
  2. Configure the Bundle Publish the default config:

    php bin/console config:dump-reference AppShed\AuthBundle
    

    Update config/packages/appshed_auth.yaml:

    appshed_auth:
        api_url: 'https://api.appshed.com/auth'
        cookie_name: 'appshed_auth_token'
        secret_key: '%env(APPSHED_SECRET_KEY)%'  # Store in .env
    
  3. First Use Case: API Login Trigger login via a controller:

    use AppShed\AuthBundle\Service\AuthService;
    
    class LoginController extends AbstractController
    {
        public function login(AuthService $authService, Request $request)
        {
            $token = $authService->loginWithCookie($request->cookies->get('appshed_auth_token'));
            // Use $token for authenticated API calls
        }
    }
    

Implementation Patterns

Workflow: Cookie-Based Authentication

  1. Frontend Integration

    • Use JavaScript to set the appshed_auth_token cookie after user login on AppShed’s platform.
    • Example (JavaScript):
      document.cookie = `appshed_auth_token=${response.token}; path=/; secure`;
      
  2. Backend Validation

    • Laravel/Symfony middleware to validate the cookie on protected routes:
      // src/EventListener/AuthListener.php
      public function onKernelRequest(GetResponseEvent $event)
      {
          $request = $event->getRequest();
          $token = $request->cookies->get('appshed_auth_token');
      
          if (!$token && !$request->isXmlHttpRequest()) {
              $authService->validateToken($token)
                  ->then(fn() => $event->setResponse(new RedirectResponse('/dashboard')))
                  ->otherwise(fn() => $event->setResponse(new RedirectResponse('/login')));
          }
      }
      
  3. API Requests Attach the token to API calls:

    $client = new Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
    $response = $client->request('GET', 'https://api.appshed.com/user');
    

Integration Tips

  • Laravel-Specific: Use Laravel’s Cookie facade for cookie handling:
    $token = request()->cookie('appshed_auth_token');
    
  • Symfony Guard: Extend AuthenticatorInterface for custom logic:
    public function supports(Request $request)
    {
        return $request->cookies->has('appshed_auth_token');
    }
    
  • Token Refresh: Implement a refreshToken() method in a service:
    $authService->refreshToken($expiredToken)->then(fn($newToken) => $this->setCookie($newToken));
    

Gotchas and Tips

Pitfalls

  1. Cookie Security

    • Issue: Missing secure/httponly flags expose tokens to XSS.
    • Fix: Set cookies via JavaScript with:
      document.cookie = `appshed_auth_token=${token}; path=/; secure; httponly; SameSite=Lax`;
      
    • Symfony: Use Response::makeCookie() with secure and httpOnly flags.
  2. Token Expiry

    • Issue: Silent failures if tokens expire without refresh logic.
    • Debug: Check AuthService::validateToken() returns false for expired tokens.
    • Fix: Implement auto-refresh in middleware:
      if (!$authService->isTokenValid($token)) {
          $authService->refreshToken($token)->wait();
      }
      
  3. API URL Mismatch

    • Issue: Hardcoded api_url in config fails in staging/prod.
    • Fix: Use environment variables:
      appshed_auth:
          api_url: '%env(APPSHED_API_URL)%'
      

Debugging

  • Log Token Responses: Enable Guzzle logging in config/packages/appshed_auth.yaml:
    appshed_auth:
        guzzle:
            debug: true
    
  • Validate Cookie Parsing: Test cookie extraction:
    $this->assertEquals(
        'expected_token',
        $request->cookies->get('appshed_auth_token')
    );
    

Extension Points

  1. Custom Token Storage Override AuthService to store tokens in a database:

    class CustomAuthService extends AuthService
    {
        public function saveToken($token, $userId)
        {
            Token::updateOrCreate(['user_id' => $userId], ['token' => $token]);
        }
    }
    
  2. Multi-Tenant Support Extend the bundle to support tenant-specific tokens:

    $authService->loginWithCookie($token, $tenantId);
    
  3. Event Dispatching Listen for auth.login.success events to trigger post-login actions:

    $dispatcher->addListener('auth.login.success', function ($token) {
        // Send welcome email, log activity, etc.
    });
    
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.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums