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

Cas Bundle Laravel Package

ecphp/cas-bundle

ecphp/cas-bundle integrates CAS (Central Authentication Service) single sign-on into Symfony applications. It bundles configuration for CAS authentication, user handling, and related services so Symfony apps can add CAS login quickly. Part of the ECphp project, with full docs available.

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.
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle
adachsoft/api-version-bundle
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
cgv/localized-resource