Skip to content

Instantly share code, notes, and snippets.

@RossIV
Last active March 25, 2021 15:09
Show Gist options
  • Save RossIV/6bedb5af7eea6905dc53 to your computer and use it in GitHub Desktop.
Save RossIV/6bedb5af7eea6905dc53 to your computer and use it in GitHub Desktop.
JASIG CAS Authentication with Laravel Lumen

##JASIG CAS Authentication with Laravel Lumen

composer.json

require {
    "jasig/phpcas": "^1.3"
}

.env

CAS_HOST=login.gatech.edu
CAS_CONTEXT=/cas

app\Http\Middleware\AuthCASMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;
use phpCAS;

class AuthCASMiddleware
{


    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $cas_config = array(
            'host' => getenv('CAS_HOST'),
            'context' => getenv('CAS_CONTEXT'),
        );

        phpCAS::client(CAS_VERSION_2_0, $cas_config['host'], 443, $cas_config['context']);
        phpCAS::setNoCasServerValidation();

        if ($request->has('logout')) {
            phpCAS::logout();
        } else if (phpCAS::isAuthenticated()) {
            return $next($request);
        } else {
            phpCAS::forceAuthentication();
        }
    }
}

bootstrap/app.php

Uncomment the array opening/closing, and insert this line as follows. This will force CAS authentication for all routes. This can be moved to $app->routeMiddleware if you want to only use it for certain routes. Just specify the middleware as documented in the Lumen docs.

$app->middleware([
    ...
    'App\Http\Middleware\AuthCASMiddleware::class',
    ...
]);

Get CAS Username

Put this function in your controller, then access the variable as seen in the example.

/**
     * Get current CAS logged-in user
     * @return bool|string GT Username if logged in, false if not
     */
    public function getCASUser() {
        if (phpCAS::isAuthenticated()) {
            return phpCAS::getUser();
        } else {
            return false;
        }
    }

Add this to your controller's return statement ->with("casUser",$this->getCASUser())

Then you can access it in a view with {{ (isset($casUser)) ? $casUser : "null" }} or just {{ $casUser }}

@zeroedin
Copy link

zeroedin commented Sep 7, 2018

Out of curiosity what version of Lumen was this for?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment