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

Phpcas Laravel Package

jasig/phpcas

phpCAS is a PHP client library for CAS (Central Authentication Service). It helps PHP apps authenticate users via a CAS server, handling login/logout redirects, validating tickets, and managing sessions with configurable SSL and server settings.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jasig/phpcas
    

    Ensure your project uses PHP 8.0+ (recommended) and OpenSSL.

  2. Basic Configuration: Create a config/cas.php file (or publish defaults via phpcas:publish):

    return [
        'client' => [
            'casServerUrl' => 'https://your-cas-server.com/cas',
            'validateUrl' => 'https://your-cas-server.com/cas/validate',
            'serviceUrl' => 'https://your-app.com/cas-callback',
            'authenticateUrl' => 'https://your-cas-server.com/cas/login',
        ],
        'debug' => env('APP_DEBUG', false),
    ];
    
  3. First Use Case: Redirect to CAS login in a Laravel controller:

    use Jasig\phpCAS\CasClient;
    
    public function login()
    {
        $cas = new CasClient();
        $cas->setNoCasServerValidation();
        $cas->forceAuthentication();
        return redirect($cas->getAuthenticationUrl());
    }
    
  4. Verify Authentication:

    public function callback()
    {
        $cas = new CasClient();
        if ($cas->validateAuthentication()) {
            $user = $cas->getAttributes();
            auth()->loginUsingId($user['uid'][0]); // Customize based on CAS attributes
            return redirect()->intended('/dashboard');
        }
        return redirect()->route('login');
    }
    

Implementation Patterns

Workflows

1. Authentication Flow

  • Pre-Auth: Redirect users to CAS login:
    $cas = new CasClient();
    $cas->forceAuthentication(); // Redirects if not authenticated
    
  • Post-Auth: Validate and map CAS attributes to Laravel:
    if ($cas->validateAuthentication()) {
        $attributes = $cas->getAttributes();
        $user = User::firstOrCreate(
            ['email' => $attributes['email'][0]],
            ['name' => $attributes['displayName'][0] ?? null]
        );
        auth()->login($user);
    }
    

2. Attribute Handling

  • Fetch Attributes:
    $attributes = $cas->getAttributes();
    // Example: $attributes['eduPersonAffiliation'][0] for institutional roles
    
  • Custom Attribute Mapping: Extend CasClient to transform attributes:
    class CustomCasClient extends \Jasig\phpCAS\CasClient {
        public function getUserData() {
            $attrs = parent::getAttributes();
            return [
                'id' => $attrs['uid'][0],
                'roles' => $attrs['eduPersonAffiliation'] ?? [],
            ];
        }
    }
    

3. Proxy Authentication

  • For service-to-service auth (e.g., API calls):
    $cas = new CasClient();
    $cas->setProxyValidation(true);
    $cas->setProxyCallbackUrl('https://your-api.com/cas-proxy-callback');
    

4. Middleware Integration

Create a HandleCasAuthentication middleware:

public function handle($request, Closure $next) {
    $cas = new CasClient();
    if (!$cas->isAuthenticated()) {
        return redirect()->route('cas.login');
    }
    return $next($request);
}

Register in app/Http/Kernel.php:

protected $routeMiddleware = [
    'cas.auth' => \App\Http\Middleware\HandleCasAuthentication::class,
];

Integration Tips

Laravel-Specific

  • Service Provider: Bind CasClient in AppServiceProvider:
    $this->app->singleton(CasClient::class, function () {
        $cas = new CasClient();
        $cas->setConfig(config('cas.client'));
        return $cas;
    });
    
  • Route Group:
    Route::middleware(['cas.auth'])->group(function () {
        // Protected routes
    });
    

Attribute Persistence

Store CAS attributes in the session or user model:

session(['cas_attributes' => $cas->getAttributes()]);
// Or attach to user model:
$user->cas_attributes = $cas->getAttributes();
$user->save();

Logging

Enable debug mode in config/cas.php:

'debug' => true,

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


Gotchas and Tips

Pitfalls

1. SSL/TLS Issues

  • Error: SSL certificate problem: self-signed certificate.
    • Fix: Disable validation (for testing only):
      $cas->setNoCasServerValidation();
      
    • Production: Ensure your CAS server uses a valid certificate. Configure CA bundle:
      $cas->setCACertPath('/path/to/ca-bundle.crt');
      

2. Service URL Mismatch

  • Error: Invalid service URL or SERVICE_VERIFIER failures.
    • Fix: Ensure serviceUrl in config matches the exact callback URL (including https/http and trailing slash).
    • Debug: Use $cas->getServiceUrl() to verify the generated URL.

3. Attribute Parsing

  • Error: Undefined array key when accessing attributes.
    • Fix: Check if attributes exist:
      $email = $cas->getAttributes()['email'][0] ?? null;
      
    • Tip: Dump raw attributes for debugging:
      dd($cas->getAttributes());
      

4. Session Handling

  • Error: Authentication fails after session timeout.
    • Fix: Regenerate session ID post-auth:
      if ($cas->validateAuthentication()) {
          $request->session()->regenerate();
      }
      

5. Proxy Validation

  • Error: PROXY_GRANTING_TICKET failures.
    • Fix: Ensure proxyCallbackUrl is set and accessible:
      $cas->setProxyCallbackUrl('https://your-app.com/cas-proxy-callback');
      

Debugging Tips

Enable Verbose Logging

$cas->setDebug(true);
$cas->setVerbose(true);

Logs will show raw CAS protocol exchanges.

Check CAS Server Logs

  • Verify CAS server logs for errors like:
    • INVALID_SERVICE
    • INVALID_TICKET
    • INTERNAL_ERROR

Test with curl

Manually test CAS endpoints:

curl --location 'https://your-cas-server.com/cas/validate' \
--header 'REMOTE_USER: testuser' \
--data-urlencode 'service=https://your-app.com/cas-callback'

Extension Points

Custom Authentication Logic

Extend CasClient to add pre/post-auth hooks:

class ExtendedCasClient extends \Jasig\phpCAS\CasClient {
    public function validateAuthentication() {
        $result = parent::validateAuthentication();
        if ($result) {
            $this->postAuthHook();
        }
        return $result;
    }

    protected function postAuthHook() {
        // Custom logic (e.g., log auth, update user)
    }
}

Attribute Filtering

Filter sensitive attributes before storing:

protected function sanitizeAttributes(array $attrs): array {
    unset($attrs['sensitiveAttribute']);
    return $attrs;
}

Multi-CAS Server Support

Use a factory pattern to switch CAS servers dynamically:

class CasFactory {
    public static function create(string $serverConfig): CasClient {
        $cas = new CasClient();
        $cas->setCasServer($serverConfig['casServerUrl']);
        $cas->setValidateServer($serverConfig['validateUrl']);
        return $cas;
    }
}

Laravel Events

Trigger events for CAS auth lifecycle:

// In your callback controller:
event(new CasAuthenticated($cas->getAttributes()));

Listen in EventServiceProvider:

protected $listen = [
    CasAuthenticated::class => [
        \App\Listeners\LogCasAuth::class,
    ],
];
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.
terminal42/code-quality-tools
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