usf-it/usf-auth

USF应用程序的SSO认证库。

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

用于USF单点登录的Composer包。此包提供三个功能

  • UsfAuthCAS 包装了 phpCAS 库,并为USF的各种CAS环境提供默认值。
  • UsfAuthToken 用于将SPA应用程序认证到USF SSO系统
  • UsfAuthHmac 使用与 HTTP-HMAC规范 兼容的方法对Web服务进行认证
  • SlimAuthMiddleware 支持在 Slim PHP框架中的认证/授权

安装

要使用composer安装USF-auth,请将以下内容添加到您的composer.json中

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

并运行 composer update

将SSL证书链从 vendor/usf-it/usf-auth/USF-CA-chain.pem 复制到 /etc/USF-CA-chain.pem

UsfAuthCAS

对开发CAS服务器进行认证并显示主用户的用户名

<?php
    use USF\auth;

    require_once 'vendor/autoload.php';

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

对生产CAS服务器进行认证并显示主用户的用户名和属性

<?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>';
      }
  }
?>

对自定义CAS服务器进行认证并显示主用户的用户名

<?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

使用应用程序ID、密钥和令牌服务URL实例化类。例如

 <?php
   use USF\auth\UsfAuthToken;

   require_once('vendor/autoload.php');

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

设置HTTP请求方法和引用

	$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);
 **/

在返回任何数据给用户之前添加这些行 之前

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

这将验证请求。如果请求是“好的”,将添加CORS头,然后处理请求的其余部分。如果不是,将向调用者返回401响应。

要访问用户主用户的用户名和属性

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

使用表示应用程序ID及其相应密钥的键值对数组实例化对象。

<?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";
}
?>

使用Guzzle 6库通过HTTP-HMAC规范请求数据

<?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

请参阅[Slim框架文档](https://slim.php.ac.cn/docs/concepts/middleware.html)以获取有关Slim中中间件系统的更多信息。

要将中间件添加到您的Slim项目并使用CAS对所有路由进行认证

<?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();

interceptUrlMap 数组元素包含HTTP方法(GET、POST等)和每个URL的列表(使用[Ant模式](https://ant.apache.ac.cn/manual/dirtasks.html)匹配),以及authN(认证)和authZ(授权)信息。

$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'
        ]
    ]
];

config.casconfig.token 数组元素包含UsfAuthCasUsfAuthToken库的配置选项。

$auth_config['config.token'] = ['app_id' => 'https://: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'
                          ];
*/