First, you download the SAML library by temporarily disabling the Yii autoloader. This is just so you can use SAML classes and methods:
<?php class YiiSAML extends CComponent { private $_yiiSAML = null; static private function pre() { require_once (Yii::app()->params['simpleSAML'] . '/lib/_autoload.php'); // temporary disable Yii autoloader spl_autoload_unregister(array( 'YiiBase', 'autoload' )); } static private function post() { // enable Yii autoloader spl_autoload_register(array( 'YiiBase', 'autoload' )); } public function __construct() { self::pre(); //We select our authentication source: $this->_yiiSAML = new SimpleSAML_Auth_Simple(Yii::app()->params['authSource']); self::post(); } static public function loggedOut($param, $stage) { self::pre(); $state = SimpleSAML_Auth_State::loadState($param, $stage); self::post(); if (isset($state['saml:sp:LogoutStatus'])) $ls = $state['saml:sp:LogoutStatus']; /* Only works for SAML SP */ else return true; return $ls['Code'] === 'urn:oasis:names:tc:SAML:2.0:status:Success' && !isset($ls['SubCode']); } public function __call($method, $args) { $params = (is_array($args) and !empty($args)) ? $args[0] : $args; if (method_exists($this->_yiiSAML, $method)) return $this->_yiiSAML->$method($params); else throw new YiiSAMLException(Yii::t('app', 'The method {method} does not exist in the SAML class', array( '{method}' => $method ))); } } class YiiSAMLException extends CException { }
Then you define a filter that extends the CFilter Yii class:
<?php Yii::import('lib.YiiSAML'); class SAMLControl extends CFilter { protected function preFilter($filterChain) { $msg = Yii::t('yii', 'You are not authorized to perform this action.'); $saml = new YiiSAML(); if (Yii::app()->user->isGuest) { Yii::app()->user->loginRequired(); return false; } else { $saml_attributes = $saml->getAttributes(); if (!$saml->isAuthenticated() or Yii::app()->user->id != $saml_attributes['User.id'][0]) { Yii::app()->user->logout(); Yii::app()->user->loginRequired(); return false; } return true; } } }
And finally, in the controllers you want to limit, you override the filters() method:
public function filters() { return array( array( 'lib.SAMLControl' ) ,
Hope this helps.
source share