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

ecphp/cas-lib

Laravel-oriented PHP CAS (Central Authentication Service) library for integrating SSO into your app. Provides CAS client features like login/logout handling, ticket validation, and user attribute retrieval, aiming for straightforward setup and compatibility with common CAS servers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ecphp/cas-lib
    

    Add to config/app.php under providers:

    Ecphp\CasLib\CasLibServiceProvider::class,
    
  2. Basic Configuration Publish the config file:

    php artisan vendor:publish --provider="Ecphp\CasLib\CasLibServiceProvider"
    

    Update config/cas.php with your CAS server details (e.g., server_url, client_id, client_secret).

  3. First Use Case: Authenticate a User

    use Ecphp\CasLib\Facades\CasLib;
    
    // Redirect user to CAS login
    $loginUrl = CasLib::getLoginUrl('/return-to-app');
    return redirect()->to($loginUrl);
    
    // Handle CAS callback (e.g., in a route)
    $ticket = request()->get('ticket');
    $user = CasLib::validateTicket($ticket);
    if ($user) {
        // Authenticate user in your app (e.g., Laravel session)
        auth()->loginUsingId($user->getId());
    }
    

Implementation Patterns

Workflows

  1. User Authentication Flow

    • Step 1: Redirect to CAS login:
      $loginUrl = CasLib::getLoginUrl(route('cas.callback'));
      
    • Step 2: Handle callback in a route:
      public function handleCasCallback()
      {
          $ticket = request()->get('ticket');
          $user = CasLib::validateTicket($ticket);
          if ($user) {
              auth()->login($user); // Customize based on your user model
          }
          return redirect()->intended('/dashboard');
      }
      
    • Step 3: Logout:
      $logoutUrl = CasLib::getLogoutUrl();
      return redirect()->to($logoutUrl);
      
  2. Service Integration

    • Laravel Middleware: Protect routes with CAS:
      public function handle($request, Closure $next)
      {
          if (!auth()->check()) {
              return redirect()->route('cas.login');
          }
          return $next($request);
      }
      
    • API Authentication: Validate tickets in API routes:
      public function apiAuth(Request $request)
      {
          $ticket = $request->bearerToken();
          $user = CasLib::validateTicket($ticket);
          if (!$user) {
              return response()->json(['error' => 'Invalid ticket'], 401);
          }
          return $next($request);
      }
      
  3. Proxy Authentication

    • Use CasLib::proxyValidateTicket() for proxy tickets (e.g., SAML-like flows):
      $proxyTicket = request()->get('proxyTicket');
      $user = CasLib::proxyValidateTicket($proxyTicket, $serviceUrl);
      

Integration Tips

  • Laravel Auth: Extend CasLibUserProvider for seamless integration:
    use Ecphp\CasLib\CasLibUserProvider;
    
    auth()->provider('cas', function ($app) {
        return new CasLibUserProvider($app['config']['cas']);
    });
    
  • Session Handling: Store CAS attributes in the session:
    session(['cas_attributes' => $user->getAttributes()]);
    
  • Attribute Mapping: Map CAS attributes to your user model:
    $user->setAttribute('email', $user->getAttribute('mail'));
    

Gotchas and Tips

Pitfalls

  1. Ticket Validation Timeouts

    • CAS tickets expire quickly (default: 5 minutes). Cache validated tickets or use short-lived sessions.
    • Fix: Extend Ecphp\CasLib\CasLib to handle stale tickets gracefully.
  2. CSRF in Callback Routes

    • The CAS callback route must accept POST requests with the ticket. Ensure your route handles both GET and POST:
      Route::post('/cas/callback', [CasController::class, 'handleCallback']);
      
  3. Attribute Parsing Issues

    • CAS attributes may be nested or malformed. Sanitize attributes before use:
      $cleanAttributes = array_map('trim', $user->getAttributes());
      
  4. Proxy Ticket Limitations

    • Proxy tickets require explicit support from the CAS server. Test thoroughly with your provider.

Debugging

  • Enable Logging Configure config/cas.php:

    'debug' => env('CAS_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  • Validate URLs Ensure service_url in config/cas.php matches the exact callback URL (including http/https and port).

  • Test with curl Manually test CAS flows:

    curl -v "https://your-cas-server/login?service=YOUR_CALLBACK_URL"
    

Extension Points

  1. Custom User Model Override CasLibUser to map attributes to your model:

    use Ecphp\CasLib\CasLibUser;
    
    class AppCasUser extends CasLibUser
    {
        public function getLaravelUser()
        {
            return User::firstOrCreate(
                ['email' => $this->getAttribute('mail')],
                ['name' => $this->getAttribute('cn')]
            );
        }
    }
    
  2. Custom Attribute Handlers Extend Ecphp\CasLib\AttributeHandler to process attributes:

    class CustomAttributeHandler extends AttributeHandler
    {
        public function handleAttributes(array $attributes)
        {
            $attributes['normalized_email'] = strtolower($attributes['mail']);
            return $attributes;
        }
    }
    

    Register in config/cas.php:

    'attribute_handler' => \App\Services\CustomAttributeHandler::class,
    
  3. Multi-CAS Server Support Use dynamic configuration for multiple CAS servers:

    CasLib::setConfig(['server_url' => env('CAS_SERVER_URL')]);
    
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.
codifyo/ts-generator-bundle
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