usf-it/usf-auth

SSO Authentication library for USF applications.

0.6.1 2018-04-10 22:00 UTC

This package is not auto-updated.

Last update: 2020-09-16 05:59:04 UTC


README

Composer package for USF Single Sign On. This package provides three functions:

  • UsfAuthCAS wraps the phpCAS library and provides defaults for the various CAS environments at USF.
  • UsfAuthToken authenticates SPA applications to the USF SSO system
  • UsfAuthHmac authenticates web services using a method compatible with the HTTP-HMAC Spec
  • SlimAuthMiddleware supports authentication/authorization in the Slim PHP framework.

Installation

To install USF-auth with composer, add this to your composer.json:

{
  "require": {
    "usf-it/usf-auth": "^0.6.0"
  }
}

and run composer update.

Copy the SSL certificate chain from vendor/usf-it/usf-auth/USF-CA-chain.pem to /etc/USF-CA-chain.pem

UsfAuthCAS

Authenticate against the development CAS server and display the principal's username:

<?php
    use USF\auth;

    require_once 'vendor/autoload.php';

    $authCAS = new auth\UsfAuthCAS();
    $authCAS->auth();
    echo $authCAS->getPrincipal()."<br\>";
?>

Authenticate against the production CAS server and display the principal's username and attributes:

<?php
  use USF\auth;

  require_once 'vendor/autoload.php';

  $authCAS = new auth\UsfAuthCAS(array('environment' => 'production'));
  $authCAS->auth();
  echo $authCAS->getPrincipal() . '<br>';
  foreach ($authCAS->getAttributes() as $key => $value) {
      if (is_array($value)) {
          echo '<li>' . $key . ':<ol>';
          foreach ($value as $item) {
              echo '<li><strong>' . $item . '</strong></li>';
          }
          echo '</ol></li>';
      } else {
          echo '<li>' . $key . ': <strong>' . $value . '</strong></li>';
      }
  }
?>

Authenticate against a custom CAS server and display the principal's username:

<?php
  use USF\auth;

  require_once('vendor/autoload.php');

  $cas_config = ['cas_host' => 'cas.example.edu',
                        'cas_port' => 443,
                        'cas_context => '/cas',
                        'ca_cert_path' => '/etc/tls/ca.pem' ];
  $authCAS = new auth\UsfAuthCAS($cas_config);
  $authCAS->auth();
  echo $authCAS->getPrincipal()."<br\>";

  // Display this if the user has the 'admin' eduPersonEntitlement
  if ($authCas->isAuthorized('admin') {
  		echo 'You are an admin!';
  }
?>

UsfAuthToken

Instantiate the class with the Application ID, Secret Key and Token Service URL. Something like:

 <?php
   use USF\auth\UsfAuthToken;

   require_once('vendor/autoload.php');

 	$at = new UsfAuthToken( 	"https://someorg.com/MyApp/",
 								"https://someauthtransferdomain.com/AuthTransferService/webtoken/" );

Set the HTTP request Method and referrer:

	$at->setRequestMethod($_SERVER['REQUEST_METHOD']);
	$at->setReferrer($_SERVER['HTTP_REFERER']);

 /** The default CORS config:
 * array(
 *  'origin' => '',
 *  'methods' => 'GET, POST, PUT, DELETE, OPTIONS',
 *  'allowCredentials' => true,
 *  'maxAge' => 86400,
 *  'allowHeaders' => 'X-Requested-With'
 * )
 *
 * If you need to change the CORS config:
 * $at->setCorsConfig($cors_config);
 **/

Add these lines before returning any data to the user:

$at->validateRequest($_SERVER['HTTP_X_AUTH_TOKEN']);
$at->addCORSheaders();

This will validate the request. If the request is 'good', the CORS headers will be added and the rest of the request will be processed. If not, it will return a 401 response to the caller.

To access the user principal's username and attributes:

echo "Username: ".$at->getPrincipal();

// Return an assoc. array of the principal's attributes
$attributes = $at->getAttributes();

// Display this if the user has the 'admin' eduPersonEntitlement
if ($at->isAuthorized('admin') {
    echo 'You are an admin!';
}

UsfAuthHmac

Instantiate the object with an array that contains one or more Key => Value pairs that represent the application ids and their corresponding secret keys.

<?php

use USF\auth\UsfAuthHmac;

require_once 'vendor/autoload.php';

$keyArray = ['apiKeyId' => 'secretKey'];

$auth = new UsfAuthHmac($keyArray);

if ($auth->authenticate()) {
    echo "Hello " . $auth->getPrincipal();
} else {
    echo "Authentication failed";
}
?>

To request data using HTTP-HMAC Spec with the Guzzle 6 library:

<?php

use Acquia\Hmac\RequestSigner;
use Acquia\Hmac\Guzzle\HmacAuthMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

require_once 'vendor/autoload.php';

$myAppKey = 'apiKeyId';
$mySecretKey = 'secretKey';

$requestSigner = new RequestSigner();
$requestSigner->setProducer('USF');  // 'USF' should be used as the producer when accessing USF applications
$middleware = new HmacAuthMiddleware($requestSigner, $myAppkey, $mySecretKey);

$stack = HandlerStack::create();
$stack->push($middleware);

$client = new Client([
    'handler' => $stack,
]);

$response = $client->get('http://example.com/resource');

echo($response->getBody());
?>

SlimAuthMiddleware

Please see the [Slim Framework Documentation] (http://www.slimframework.com/docs/concepts/middleware.html) for more information on the Middleware system in Slim.

To add the middleware to your Slim project and use CAS for all routes:

<?php
use \USF\auth\PSR7\USFAuthMiddleware;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';

$configuration = [
    'settings' => [
        'displayErrorDetails' => true,
    ],
];
$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);

//Set authentication config
$auth_config = [
    'config.cas' => ['environment' => 'development'],
    'interceptUrlMap'  => ['GET' => ['/**' => ['authN' => 'CAS', 'authZ' => 'permitAll']]]
];

//Add the Auth Middleware
$app->add(new USFAuthMiddleware($auth_config));

$app->get('/foo', function (Request $request, Response $response) use ($app) {
    $response->getBody()->write("Hello ".$request->getHeaderLine('AUTH_PRINCIPAL'));
    return $response;
});
$app->run();

The interceptUrlMap array element contains a list of the HTTP methods (GET, POST, etc) and the URLs for each (using [Ant pattern] (https://ant.apache.org/manual/dirtasks.html) matching), along with authN (authentication) and authZ (authorization) information.

$auth_config['interceptUrlMap'] = [
    'GET' => [
        // GET /api/* routes
        '/api/**' => [
            'authN' => 'token', //Use UsfAuthToken
            'authZ' => ['admin','user'] // allow users with these entitlements
        ],
        // all other GET routes
        '/**' => [
            'authN' => 'CAS', //authenticate with CAS, allow everyone
            'authZ' => 'permitAll'
        ]
    ],
    'POST' => [
        // all POST routes
        '/**' => [
            'authN' => 'denyAll', //deny everyone
            'authZ' => 'denyAll'
        ]
    ],
    'PUT' => [
        // all PUT routes
        '/**' => [
            'authN' => 'denyAll', //deny everyone
            'authZ' => 'denyAll'
        ]
    ],
    'DELETE' => [
        // all DELETE routes
        '/**' => [
            'authN' => 'denyAll', //deny everyone
            'authZ' => 'denyAll'
        ]
    ],
    'OPTIONS' => [
        // all OPTIONS routes
        '/**' => [
            'authN' => 'denyAll', //deny everyone
            'authZ' => 'denyAll'
        ]
    ]
];

The config.cas and config.token array elements contain the config options for the UsfAuthCas and UsfAuthToken libraries.

$auth_config['config.token'] = ['app_id' => 'http://localhost:8080/app',
                                   'token_url' => 'https://someauthtransferdomain.com/AuthTransferService/webtoken/'];

// Using the shorthand for USF CAS environments
$auth_config['config.cas'] = ['environment' => 'production'];

/* using custom CAS config:
$auth_config['config.cas'] = ['cas_host' => 'cas.example.edu',
                        	  'cas_port' => 443,
                        	  'cas_context => '/cas',
                        	  'ca_cert_path' => '/etc/tls/ca.pem'
                          ];
*/