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

Cas Bundle Laravel Package

ecphp/cas-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ecphp/cas-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Ecphp\CasBundle\EcphpCasBundle::class => ['all' => true],
    ];
    
  2. Configuration Update config/packages/ecphp_cas.yaml:

    ecphp_cas:
        client:
            cas_server_url: 'https://your-cas-server/cas'
            authentication_url: '/cas/login'
            validation_url: '/cas/serviceValidate'
            logout_url: '/cas/logout'
        user:
            class: App\Entity\User
            property: username
    
  3. First Use Case Secure a route with CAS authentication:

    # config/packages/security.yaml
    security:
        firewalls:
            main:
                pattern: ^/
                cas:
                    entry_point: cas_authentication_entry_point
                    provider: cas_user_provider
    

Key Files to Review

  • config/packages/ecphp_cas.yaml (core settings)
  • src/Security/CasUserProvider.php (custom user mapping)
  • src/Security/CasAuthenticationEntryPoint.php (custom entry point)

Implementation Patterns

Core Workflows

1. User Authentication Flow

// In a controller or event subscriber
use Ecphp\CasBundle\Security\CasUserProvider;

// Fetch authenticated user
$user = $this->get('security.token_storage')->getToken()->getUser();
if ($user instanceof CasUserInterface) {
    $casUser = $this->get(CasUserProvider::class)->loadUserByUsername($user->getUsername());
    // Custom logic with CAS attributes
}

2. Attribute Handling

Access CAS-provided attributes:

$attributes = $user->getAttributes();
$email = $attributes->get('email') ?? null;

3. Custom User Mapping

Extend CasUserProvider to map CAS responses to your user model:

use Ecphp\CasBundle\Security\CasUserProvider as BaseCasUserProvider;

class CustomCasUserProvider extends BaseCasUserProvider
{
    public function loadUserByUsername($username)
    {
        $casUser = parent::loadUserByUsername($username);
        $user = $this->userRepository->findOneBy(['username' => $username]);

        if (!$user) {
            $user = $this->userRepository->createNew();
            $user->setUsername($username);
            $user->setEmail($casUser->getAttributes()->get('email'));
            $this->userRepository->save($user);
        }

        return $user;
    }
}

4. Logout Handling

# config/packages/security.yaml
security:
    firewalls:
        main:
            pattern: ^/
            cas:
                logout:
                    invalidate_session: true
                    post_logout_redirect: /logout-success

Integration Tips

Symfony Security Integration

  • Use cas_authenticator in your firewall configuration.
  • Leverage Symfony’s UserCheckerInterface for post-authentication checks:
    public function checkPostAuth(UserInterface $user)
    {
        if (!$user->hasAttribute('isActive')) {
            throw new DisabledException('Account is disabled.');
        }
    }
    

Attribute-Based Access Control (ABAC)

// In a voter
public function vote(TokenInterface $token, $object, array $attributes)
{
    $user = $token->getUser();
    $requiredRole = $attributes[0];

    if ($user->getAttributes()->has('roles')) {
        $userRoles = $user->getAttributes()->get('roles');
        return in_array($requiredRole, $userRoles, true);
    }

    return false;
}

Debugging CAS Responses

Enable debug mode in config/packages/ecphp_cas.yaml:

ecphp_cas:
    debug: true

Gotchas and Tips

Common Pitfalls

  1. CORS Issues with CAS Server

    • Ensure your CAS server allows requests from your Symfony domain.
    • Configure CORS headers if using a separate frontend:
      # config/packages/ecphp_cas.yaml
      ecphp_cas:
          client:
              allowed_origins: ['https://your-frontend.com']
      
  2. Attribute Parsing Failures

    • CAS attributes may arrive in different formats (JSON, XML, or raw strings).
    • Override CasUser::getAttributes() to handle custom formats:
      public function getAttributes()
      {
          if ($this->attributes === null) {
              $this->attributes = new AttributesCollection(
                  json_decode($this->rawAttributes, true)
              );
          }
          return $this->attributes;
      }
      
  3. Session Fixation

    • Always regenerate session IDs after CAS authentication:
      # config/packages/security.yaml
      security:
          firewalls:
              main:
                  cas:
                      regenerate_session: true
      
  4. Proxy Server Issues

    • If behind a proxy, ensure trusted_proxies is configured:
      # config/packages/framework.yaml
      framework:
          trusted_proxies:
              - 192.168.0.0/16
      

Debugging Tips

  1. Enable Verbose Logging

    # config/packages/ecphp_cas.yaml
    ecphp_cas:
        debug: true
        logging:
            level: debug
    
  2. Inspect CAS Responses

    • Use a browser extension (e.g., ModHeader) to inspect the serviceValidate POST request.
    • Check Symfony logs for raw CAS XML/JSON responses.
  3. Test with a Mock CAS Server

Configuration Quirks

  1. URL Paths Must Match Exactly

    • Ensure authentication_url, validation_url, and logout_url match your CAS server’s endpoints exactly (including trailing slashes).
  2. HTTPS Requirements

    • CAS servers often enforce HTTPS. Configure Symfony to redirect HTTP to HTTPS:
      # config/packages/framework.yaml
      framework:
          router:
              http_port: 80
              https_port: 443
              redirect_http_to_https: true
      
  3. User Provider Overrides

    • If extending CasUserProvider, ensure your custom provider is registered as a service:
      # config/services.yaml
      services:
          App\Security\CustomCasUserProvider:
              tags: ['security.user_provider']
      

Extension Points

  1. Custom Attribute Handlers

    • Implement Ecphp\CasBundle\Security\AttributeHandlerInterface to transform raw attributes:
      class CustomAttributeHandler implements AttributeHandlerInterface
      {
          public function handle(array $attributes, UserInterface $user)
          {
              $attributes['normalized_email'] = strtolower($attributes['email'] ?? '');
              return $attributes;
          }
      }
      
      Register in config/packages/ecphp_cas.yaml:
      ecphp_cas:
          attribute_handlers:
              - App\Security\CustomAttributeHandler
      
  2. Event Listeners

    • Listen to CAS authentication events:
      use Ecphp\CasBundle\Event\CasEvents;
      use Symfony\Component\EventDispatcher\GenericEvent;
      
      $dispatcher->addListener(CasEvents::AUTHENTICATION_SUCCESS, function (GenericEvent $event) {
          $user = $event->getSubject();
          // Custom logic on successful auth
      });
      
  3. Custom Entry Point

    • Override the default CAS login page:
      use Ecphp\CasBundle\Security\CasAuthenticationEntryPoint;
      
      class CustomCasEntryPoint extends CasAuthenticationEntryPoint
      {
          public function start(Request $request = null, ?string $message = null)
          {
              return new RedirectResponse('/custom-cas-login');
          }
      }
      
      Register in config/packages/security.yaml:
      security:
          firewalls:
              main:
                  cas:
                      entry_point: custom_cas_entry_point
      
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views