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 Connection Laravel Package

dsi-iepg/cas-connection

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require dsi-iepg/cas-connection
    
  2. Configure the Bundle Add to config/bundles.php:

    return [
        // ...
        Iepg\Bundle\Cas\CasConnectionBundle::class => ['all' => true],
    ];
    
  3. Set CAS Environment Variables Add to .env:

    CAS_HOST=your-cas-server.com
    CAS_PORT=443
    
  4. Create a CAS-Compatible User Entity Generate a User entity with a login field (no password):

    php bin/console make:user
    
    • Name: User
    • Store in DB: yes
    • Property: login
    • Password: no
  5. Run Migrations

    php bin/console make:migration
    php bin/console doctrine:migrations:migrate
    
  6. First Test Access your app’s login route (e.g., /login). The bundle should redirect to the CAS server for authentication.


First Use Case: Basic CAS Login Flow

  • A user visits /login → redirected to CAS server.
  • CAS authenticates the user → redirects back to your app with a ticket.
  • The bundle validates the ticket, creates/updates a User record with the CAS-provided login, and logs them in.

Implementation Patterns

Workflow: Integrating CAS Authentication

  1. User Authentication Flow

    • The bundle handles the CAS redirect/validation automatically. Override Iepg\Bundle\Cas\Security\CASAuthenticator if custom logic is needed (e.g., role assignment).
    • Example: Extend the authenticator to assign roles dynamically:
      // src/Security/CustomCASAuthenticator.php
      namespace App\Security;
      
      use Iepg\Bundle\Cas\Security\CASAuthenticator as BaseAuthenticator;
      
      class CustomCASAuthenticator extends BaseAuthenticator {
          public function getUserRoles($login) {
              // Fetch roles from a service or DB
              return ['ROLE_USER', 'ROLE_ADMIN']; // Example
          }
      }
      
    • Register the custom authenticator in config/packages/security.yaml:
      security:
          firewalls:
              main:
                  authenticator: App\Security\CustomCASAuthenticator
      
  2. User Entity Customization

    • Extend the default User entity to add CAS-specific fields (e.g., casAttributes):
      // src/Entity/User.php
      use Doctrine\ORM\Mapping as ORM;
      
      #[ORM\Entity]
      class User {
          // ...
          #[ORM\Column(type: 'json', nullable: true)]
          private ?array $casAttributes = [];
      
          public function setCasAttributes(array $attributes): self {
              $this->casAttributes = $attributes;
              return $this;
          }
      }
      
    • Update the authenticator to populate these fields:
      // In CustomCASAuthenticator
      public function getUser($credentials, UserProviderInterface $userProvider) {
          $user = parent::getUser($credentials, $userProvider);
          $user->setCasAttributes($this->fetchCasAttributesFromServer());
          return $user;
      }
      
  3. Multi-Tenant or Role-Based Access

    • Use the USER/ADMIN roles to gate routes:
      # config/routes.yaml
      admin:
          path: /admin
          controller: App\Controller\AdminController::index
          roles: ROLE_ADMIN
      
    • Dynamically assign roles based on CAS attributes (e.g., group membership):
      // In CustomCASAuthenticator
      public function getUserRoles($login) {
          $casAttributes = $this->fetchCasAttributes($login);
          return $casAttributes['groups'] ?? ['ROLE_USER'];
      }
      
  4. Logout Handling

    • The bundle supports CAS logout. Extend the logout logic if needed:
      // In CustomCASAuthenticator
      public function onLogoutSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response {
          // Add custom logout logic (e.g., invalidate sessions)
          return parent::onLogoutSuccess($request, $token, $firewallName);
      }
      

Integration Tips

  • Symfony Security Integration: The bundle works seamlessly with Symfony’s security component. Use security.yaml to configure firewalls, access control, and providers.
  • CAS Server Configuration: Ensure your CAS server is configured to:
    • Accept the callback URL (e.g., https://your-app.com/login_check).
    • Return the login attribute in the CAS response (required by the bundle).
  • Testing: Use the php-cas library to mock CAS responses in PHPUnit tests:
    // tests/Functional/CASAuthTest.php
    use PHP_CAS;
    
    public function testCasLogin() {
        PHP_CAS::setServer('https://test-cas.com');
        PHP_CAS::setNoCasServerValidation();
        // Test login flow
    }
    
  • Environment-Specific Config: Use Symfony’s parameter bags to override CAS settings per environment:
    # config/packages/cas.yaml
    parameters:
        cas_host: '%env(CAS_HOST)%'
        cas_port: '%env(int:CAS_PORT)%'
    

Gotchas and Tips

Pitfalls

  1. Missing login Field

    • The bundle requires a login field in the User entity. If omitted, authentication will fail silently.
    • Fix: Regenerate the User entity with the login property or manually add it.
  2. CAS Server Mismatch

    • If CAS_HOST or CAS_PORT are misconfigured, the bundle will throw a RuntimeException.
    • Debug: Check the Symfony profiler for CAS-related errors or enable debug logging:
      CAS_DEBUG=true
      
  3. Certificate Validation Issues

    • If CAS_CA=true but the certificate is invalid, the bundle will fail with a PHP_CAS_Exception.
    • Fix: Provide a valid CA bundle path (CAS_CA_PATH) or disable validation in development:
      CAS_CA=false  # Only for testing!
      
  4. Role Assignment Conflicts

    • The bundle hardcodes USER and ADMIN roles. Overriding these without updating the authenticator can cause role mismatches.
    • Fix: Extend the authenticator to use custom role logic (as shown in Implementation Patterns).
  5. Session Fixation

    • CAS authentication may not invalidate existing sessions by default. Use Symfony’s stateless: true or session fixation protection:
      # config/packages/security.yaml
      firewalls:
          main:
              stateless: true
      
  6. CSRF Token Mismatch

    • If using Symfony’s CSRF protection, ensure the CAS callback includes the _csrf_token in the session.
    • Fix: Disable CSRF for the CAS route or configure the authenticator to handle it:
      # config/packages/security.yaml
      firewalls:
          main:
              form_login:
                  csrf_token_generator: security.csrf.token_manager
      

Debugging Tips

  1. Enable CAS Debug Mode Add to .env:

    CAS_DEBUG=true
    

    This logs CAS requests/responses to var/log/dev.log.

  2. Inspect the CAS Response Dump the CAS ticket or attributes in the authenticator:

    // In CustomCASAuthenticator
    public function getUser($credentials, UserProviderInterface $userProvider) {
        dump($credentials); // Shows CAS response data
        // ...
    }
    
  3. Validate CAS Server Test the CAS server independently using php-cas:

    use PHP_CAS;
    
    PHP_CAS::client(CAS_VERSION_2_0, 'your-app.com', 443, 'cas-server.com');
    if (PHP_CAS::isAuthenticated()) {
        echo "Authenticated as: " . PHP_CAS::getUser();
    }
    
  4. Check Doctrine Events Listen for prePersist/preUpdate on the User entity to debug CAS attribute mapping:

    // src/EventListener/UserListener.php
    namespace App\EventListener;
    
    use Doctrine\ORM\Event\LifecycleEventArgs;
    
    class UserListener {
        public function prePersist(User $user, LifecycleEventArgs $args) {
            dump($user->getCasAttributes());
        }
    }
    

    Register the listener in services.yaml:

    services:
        App\EventListener\UserListener:
            tags:
                - { name: doctrine.event_listener, event: prePersist }
    

Extension Points

  1. Custom User Provider Replace the default UserProvider to fetch users from an external source (e.g., LDAP
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope