Class yii\authclient\OpenId
Inheritance | yii\authclient\OpenId » yii\authclient\BaseClient » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\authclient\ClientInterface, yii\base\Configurable |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-authclient/blob/master/OpenId.php |
OpenId provides a simple interface for OpenID (1.1 and 2.0) authentication.
Supports Yadis and HTML discovery.
Usage:
use yii\authclient\OpenId;
$client = new OpenId();
$client->authUrl = 'https://open.id.provider.url'; // Setup provider endpoint
$url = $client->buildAuthUrl(); // Get authentication URL
return Yii::$app->getResponse()->redirect($url); // Redirect to authentication URL
// After user returns at our site:
if ($client->validate()) { // validate response
$userAttributes = $client->getUserAttributes(); // get account info
...
}
AX and SREG extensions are supported. To use them, specify $requiredAttributes and/or $optionalAttributes.
See also https://openid.net/.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$authUrl | string | Authentication base URL, which should be used to compose actual authentication URL by buildAuthUrl() method. | yii\authclient\OpenId |
$axToSregMap | array | Map of matches between AX and SREG attribute names in format: axAttributeName => sregAttributeName | yii\authclient\OpenId |
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component. | yii\base\Component |
$cainfo | string | The name of a file holding one or more certificates to verify the peer with. | yii\authclient\OpenId |
$capath | string | Directory that holds multiple CA certificates. | yii\authclient\OpenId |
$claimedId | string | Claimed identifier (identity). | yii\authclient\OpenId |
$data | array | Data, which should be used to retrieve the OpenID response. | yii\authclient\OpenId |
$httpClient | yii\httpclient\Client | Internal HTTP client. | yii\authclient\BaseClient |
$id | string | Service id. | yii\authclient\BaseClient |
$name | string | Service name. | yii\authclient\BaseClient |
$normalizeUserAttributeMap | array | Normalize user attribute map. | yii\authclient\BaseClient |
$optionalAttributes | array | List of attributes, which could be returned from server. | yii\authclient\OpenId |
$requestOptions | array | HTTP request options. | yii\authclient\BaseClient |
$requiredAttributes | array | List of attributes, which always should be returned from server. | yii\authclient\OpenId |
$returnUrl | string | Authentication return URL. | yii\authclient\OpenId |
$stateStorage | yii\authclient\StateStorageInterface | Stage storage. | yii\authclient\BaseClient |
$title | string | Service title. | yii\authclient\BaseClient |
$trustRoot | string | Client trust root (realm). | yii\authclient\OpenId |
$userAttributes | array | List of user attributes. | yii\authclient\BaseClient |
$verifyPeer | boolean | Whether to verify the peer's certificate. | yii\authclient\OpenId |
$viewOptions | array | View options in format: optionName => optionValue. | yii\authclient\BaseClient |
Public Methods
Protected Methods
Method | Description | Defined By |
---|---|---|
buildAuthUrlV1() | Builds authentication URL for the protocol version 1. | yii\authclient\OpenId |
buildAuthUrlV2() | Builds authentication URL for the protocol version 2. | yii\authclient\OpenId |
buildAxParams() | Composes AX request parameters. | yii\authclient\OpenId |
buildSregParams() | Composes SREG request parameters. | yii\authclient\OpenId |
buildUrl() | Combines given URLs into single one. | yii\authclient\OpenId |
compareUrl() | Compares 2 URLs taking in account possible GET parameters order miss match and URL encoding inconsistencies. | yii\authclient\OpenId |
createHttpClient() | Creates HTTP client instance from reference or configuration. | yii\authclient\BaseClient |
defaultName() | Generates service name. | yii\authclient\BaseClient |
defaultNormalizeUserAttributeMap() | Returns the default $normalizeUserAttributeMap value. | yii\authclient\BaseClient |
defaultRequestOptions() | Returns default HTTP request options. | yii\authclient\OpenId |
defaultReturnUrl() | Generates default $returnUrl value. | yii\authclient\OpenId |
defaultTitle() | Generates service title. | yii\authclient\BaseClient |
defaultViewOptions() | Returns the default $viewOptions value. | yii\authclient\BaseClient |
extractHtmlTagValue() | Scans content for / tags and extract information from them. | yii\authclient\OpenId |
fetchAxAttributes() | Gets AX attributes provided by OP. | yii\authclient\OpenId |
fetchSregAttributes() | Gets SREG attributes provided by OP. SREG names will be mapped to AX names. | yii\authclient\OpenId |
getState() | Returns persistent state value. | yii\authclient\BaseClient |
getStateKeyPrefix() | Returns session key prefix, which is used to store internal states. | yii\authclient\BaseClient |
initUserAttributes() | Initializes authenticated user attributes. | yii\authclient\OpenId |
normalizeUserAttributes() | Normalize given user attributes according to $normalizeUserAttributeMap. | yii\authclient\BaseClient |
removeState() | Removes persistent state value. | yii\authclient\BaseClient |
sendRequest() | Sends request to the server | yii\authclient\OpenId |
setState() | Sets persistent state. | yii\authclient\BaseClient |
validateRequiredAttributes() | Checks if all required attributes are present in the server response. | yii\authclient\OpenId |
Property Details
Authentication base URL, which should be used to compose actual authentication URL by buildAuthUrl() method.
Map of matches between AX and SREG attribute names in format: axAttributeName => sregAttributeName
'namePerson/friendly' => 'nickname',
'contact/email' => 'email',
'namePerson' => 'fullname',
'birthDate' => 'dob',
'person/gender' => 'gender',
'contact/postalCode/home' => 'postcode',
'contact/country/home' => 'country',
'pref/language' => 'language',
'pref/timezone' => 'timezone',
]
The name of a file holding one or more certificates to verify the peer with. This value will take effect only if $verifyPeer is set.
Directory that holds multiple CA certificates. This value will take effect only if $verifyPeer is set.
Data, which should be used to retrieve the OpenID response. If not set combination of GET and POST will be used.
List of attributes, which could be returned from server. Attribute names should be always specified in AX format. For example:
['namePerson/first', 'namePerson/last']
List of attributes, which always should be returned from server. Attribute names should be always specified in AX format. For example:
['namePerson/friendly', 'contact/email']
Whether to verify the peer's certificate.
Method Details
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
public mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\base\Component::__clone()
This method is called after the object is created by cloning an existing one.
It removes all behaviors because they are attached to the old object.
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call init().
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
public void __construct ( $config = [] ) | ||
$config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
Returns the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
See also __set().
public mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value or the value of a behavior's property |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
Checks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
See also __get().
public void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::attachBehavior()
Attaches a behavior to this component.
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the yii\base\Behavior::attach() method.
See also detachBehavior().
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
The name of the behavior. |
$behavior | string|array|yii\base\Behavior |
The behavior configuration. This can be one of the following:
|
return | yii\base\Behavior |
The behavior object |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
Attaches a list of behaviors to the component.
Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.
See also attachBehavior().
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
public array behaviors ( ) | ||
return | array |
The behavior configurations. |
---|
public function behaviors()
{
return [];
}
Returns authentication URL. Usually, you want to redirect your user to it.
public string buildAuthUrl ( $identifierSelect = null ) | ||
$identifierSelect | boolean |
Whether to request OP to select identity for an user in OpenID 2, does not affect OpenID 1. |
return | string |
The authentication URL. |
---|---|---|
throws | yii\base\Exception |
on failure. |
public function buildAuthUrl($identifierSelect = null)
{
$authUrl = $this->authUrl;
$claimedId = $this->getClaimedId();
if (empty($claimedId)) {
$this->setClaimedId($authUrl);
}
$serverInfo = $this->discover($authUrl);
if ($serverInfo['version'] == 2) {
if ($identifierSelect !== null) {
$serverInfo['identifier_select'] = $identifierSelect;
}
return $this->buildAuthUrlV2($serverInfo);
}
return $this->buildAuthUrlV1($serverInfo);
}
Builds authentication URL for the protocol version 1.
protected string buildAuthUrlV1 ( $serverInfo ) | ||
$serverInfo | array |
OpenID server info. |
return | string |
Authentication URL. |
---|
protected function buildAuthUrlV1($serverInfo)
{
$returnUrl = $this->getReturnUrl();
/* If we have an openid.delegate that is different from our claimed id,
we need to somehow preserve the claimed id between requests.
The simplest way is to just send it along with the return_to url.*/
if ($serverInfo['identity'] != $this->getClaimedId()) {
$returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->getClaimedId();
}
$params = array_merge(
[
'openid.return_to' => $returnUrl,
'openid.mode' => 'checkid_setup',
'openid.identity' => $serverInfo['identity'],
'openid.trust_root' => $this->trustRoot,
],
$this->buildSregParams()
);
return $this->buildUrl($serverInfo['url'], ['query' => http_build_query($params, '', '&')]);
}
Builds authentication URL for the protocol version 2.
protected string buildAuthUrlV2 ( $serverInfo ) | ||
$serverInfo | array |
OpenID server info. |
return | string |
Authentication URL. |
---|
protected function buildAuthUrlV2($serverInfo)
{
$params = [
'openid.ns' => 'http://specs.openid.net/auth/2.0',
'openid.mode' => 'checkid_setup',
'openid.return_to' => $this->getReturnUrl(),
'openid.realm' => $this->getTrustRoot(),
];
if ($serverInfo['ax']) {
$params = array_merge($params, $this->buildAxParams());
}
if ($serverInfo['sreg']) {
$params = array_merge($params, $this->buildSregParams());
}
if (!$serverInfo['ax'] && !$serverInfo['sreg']) {
// If OP doesn't advertise either SREG, nor AX, let's send them both in worst case we don't get anything in return.
$params = array_merge($this->buildSregParams(), $this->buildAxParams(), $params);
}
if ($serverInfo['identifier_select']) {
$url = 'http://specs.openid.net/auth/2.0/identifier_select';
$params['openid.identity'] = $url;
$params['openid.claimed_id']= $url;
} else {
$params['openid.identity'] = $serverInfo['identity'];
$params['openid.claimed_id'] = $this->getClaimedId();
}
return $this->buildUrl($serverInfo['url'], ['query' => http_build_query($params, '', '&')]);
}
Composes AX request parameters.
protected array buildAxParams ( ) | ||
return | array |
AX parameters. |
---|
protected function buildAxParams()
{
$params = [];
if (!empty($this->requiredAttributes) || !empty($this->optionalAttributes)) {
$params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
$params['openid.ax.mode'] = 'fetch_request';
$aliases = [];
$counts = [];
$requiredAttributes = [];
$optionalAttributes = [];
foreach (['requiredAttributes', 'optionalAttributes'] as $type) {
foreach ($this->$type as $alias => $field) {
if (is_int($alias)) {
$alias = strtr($field, '/', '_');
}
$aliases[$alias] = 'http://axschema.org/' . $field;
if (empty($counts[$alias])) {
$counts[$alias] = 0;
}
$counts[$alias] += 1;
${$type}[] = $alias;
}
}
foreach ($aliases as $alias => $ns) {
$params['openid.ax.type.' . $alias] = $ns;
}
foreach ($counts as $alias => $count) {
if ($count == 1) {
continue;
}
$params['openid.ax.count.' . $alias] = $count;
}
// Don't send empty ax.required and ax.if_available.
// Google and possibly other providers refuse to support ax when one of these is empty.
if (!empty($requiredAttributes)) {
$params['openid.ax.required'] = implode(',', $requiredAttributes);
}
if (!empty($optionalAttributes)) {
$params['openid.ax.if_available'] = implode(',', $optionalAttributes);
}
}
return $params;
}
Composes SREG request parameters.
protected array buildSregParams ( ) | ||
return | array |
SREG parameters. |
---|
protected function buildSregParams()
{
$params = [];
/* We always use SREG 1.1, even if the server is advertising only support for 1.0.
That's because it's fully backwards compatible with 1.0, and some providers
advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com */
$params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
if (!empty($this->requiredAttributes)) {
$params['openid.sreg.required'] = [];
foreach ($this->requiredAttributes as $required) {
if (!isset($this->axToSregMap[$required])) {
continue;
}
$params['openid.sreg.required'][] = $this->axToSregMap[$required];
}
$params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
}
if (!empty($this->optionalAttributes)) {
$params['openid.sreg.optional'] = [];
foreach ($this->optionalAttributes as $optional) {
if (!isset($this->axToSregMap[$optional])) {
continue;
}
$params['openid.sreg.optional'][] = $this->axToSregMap[$optional];
}
$params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
}
return $params;
}
Combines given URLs into single one.
protected string buildUrl ( $baseUrl, $additionalUrl ) | ||
$baseUrl | string |
Base URL. |
$additionalUrl | string|array |
Additional URL string or information array. |
return | string |
Composed URL. |
---|
protected function buildUrl($baseUrl, $additionalUrl)
{
$baseUrl = parse_url($baseUrl);
if (!is_array($additionalUrl)) {
$additionalUrl = parse_url($additionalUrl);
}
if (isset($baseUrl['query'], $additionalUrl['query'])) {
$additionalUrl['query'] = $baseUrl['query'] . '&' . $additionalUrl['query'];
}
$urlInfo = array_merge($baseUrl, $additionalUrl);
$url = $urlInfo['scheme'] . '://'
. (empty($urlInfo['username']) ? ''
:(empty($urlInfo['password']) ? "{$urlInfo['username']}@"
:"{$urlInfo['username']}:{$urlInfo['password']}@"))
. $urlInfo['host']
. (empty($urlInfo['port']) ? '' : ":{$urlInfo['port']}")
. (empty($urlInfo['path']) ? '' : $urlInfo['path'])
. (empty($urlInfo['query']) ? '' : "?{$urlInfo['query']}")
. (empty($urlInfo['fragment']) ? '' : "#{$urlInfo['fragment']}");
return $url;
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
Compares 2 URLs taking in account possible GET parameters order miss match and URL encoding inconsistencies.
protected boolean compareUrl ( $expectedUrl, $actualUrl ) | ||
$expectedUrl | string |
Expected URL. |
$actualUrl | string |
Actual URL. |
return | boolean |
Whether URLs are equal. |
---|
protected function compareUrl($expectedUrl, $actualUrl)
{
$expectedUrlInfo = parse_url($expectedUrl);
$actualUrlInfo = parse_url($actualUrl);
foreach ($expectedUrlInfo as $name => $expectedValue) {
if ($name == 'query') {
parse_str($expectedValue, $expectedUrlParams);
parse_str($actualUrlInfo[$name], $actualUrlParams);
$paramsDiff = array_diff_assoc($expectedUrlParams, $actualUrlParams);
if (!empty($paramsDiff)) {
return false;
}
} elseif ($expectedValue != $actualUrlInfo[$name]) {
return false;
}
}
return true;
}
Defined in: yii\authclient\BaseClient::createHttpClient()
Creates HTTP client instance from reference or configuration.
protected yii\httpclient\Client createHttpClient ( $reference ) | ||
$reference | string|array |
Component name or array configuration. |
return | yii\httpclient\Client |
HTTP client instance. |
---|
protected function createHttpClient($reference)
{
return Instance::ensure($reference, Client::className());
}
Defined in: yii\authclient\BaseClient::createRequest()
Creates HTTP request instance.
public yii\httpclient\Request createRequest ( ) | ||
return | yii\httpclient\Request |
HTTP request instance. |
---|
public function createRequest()
{
return $this->getHttpClient()
->createRequest()
->addOptions($this->defaultRequestOptions())
->addOptions($this->getRequestOptions());
}
Defined in: yii\authclient\BaseClient::defaultName()
Generates service name.
protected string defaultName ( ) | ||
return | string |
Service name. |
---|
protected function defaultName()
{
return Inflector::camel2id(StringHelper::basename(get_class($this)));
}
Defined in: yii\authclient\BaseClient::defaultNormalizeUserAttributeMap()
Returns the default $normalizeUserAttributeMap value.
Particular client may override this method in order to provide specific default map.
protected array defaultNormalizeUserAttributeMap ( ) | ||
return | array |
Normalize attribute map. |
---|
protected function defaultNormalizeUserAttributeMap()
{
return [];
}
Returns default HTTP request options.
protected array defaultRequestOptions ( ) | ||
return | array |
HTTP request options. |
---|
protected function defaultRequestOptions()
{
return [
'userAgent' => Yii::$app->name . ' OpenID Client',
'timeout' => 30,
'followLocation' => true,
];
}
Generates default $returnUrl value.
protected string defaultReturnUrl ( ) | ||
return | string |
Default authentication return URL. |
---|
protected function defaultReturnUrl()
{
$params = Yii::$app->getRequest()->get();
foreach ($params as $name => $value) {
if (strncmp('openid', $name, 6) === 0) {
unset($params[$name]);
}
}
$params[0] = Yii::$app->requestedRoute;
$url = Yii::$app->getUrlManager()->createUrl($params);
return $this->getTrustRoot() . $url;
}
Defined in: yii\authclient\BaseClient::defaultTitle()
Generates service title.
protected string defaultTitle ( ) | ||
return | string |
Service title. |
---|
protected function defaultTitle()
{
return StringHelper::basename(get_class($this));
}
Defined in: yii\authclient\BaseClient::defaultViewOptions()
Returns the default $viewOptions value.
Particular client may override this method in order to provide specific default view options.
protected array defaultViewOptions ( ) | ||
return | array |
List of default $viewOptions |
---|
protected function defaultViewOptions()
{
return [];
}
Defined in: yii\base\Component::detachBehavior()
Detaches a behavior from the component.
The behavior's yii\base\Behavior::detach() method will be invoked.
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
The behavior's name. |
return | yii\base\Behavior|null |
The detached behavior. Null if the behavior does not exist. |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
Detaches all behaviors from the component.
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Performs Yadis and HTML discovery.
public array discover ( $url ) | ||
$url | string |
Identity URL. |
return | array |
OpenID provider info, following keys will be available:
|
---|---|---|
throws | yii\base\Exception |
on failure. |
public function discover($url)
{
if (empty($url)) {
throw new Exception('No identity supplied.');
}
$result = [
'url' => null,
'version' => null,
'identity' => $url,
'identifier_select' => false,
'ax' => false,
'sreg' => false,
];
// Use xri.net proxy to resolve i-name identities
if (!preg_match('#^https?:#', $url)) {
$url = 'https://xri.net/' . $url;
}
/* We save the original url in case of Yadis discovery failure.
It can happen when we'll be lead to an XRDS document
which does not have any OpenID2 services.*/
$originalUrl = $url;
// A flag to disable yadis discovery in case of failure in headers.
$yadis = true;
// We'll jump a maximum of 5 times, to avoid endless redirections.
for ($i = 0; $i < 5; $i ++) {
if ($yadis) {
$headers = $this->sendRequest($url, 'HEAD');
$next = false;
if (isset($headers['x-xrds-location'])) {
$url = $this->buildUrl($url, trim($headers['x-xrds-location']));
$next = true;
}
if (isset($headers['content-type'])
&& (strpos($headers['content-type'], 'application/xrds+xml') !== false
|| strpos($headers['content-type'], 'text/xml') !== false)
) {
/* Apparently, some providers return XRDS documents as text/html.
While it is against the spec, allowing this here shouldn't break
compatibility with anything.
---
Found an XRDS document, now let's find the server, and optionally delegate.*/
$content = $this->sendRequest($url, 'GET');
preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m);
foreach ($m[1] as $content) {
$content = ' ' . $content; // The space is added, so that strpos doesn't return 0.
// OpenID 2
$ns = preg_quote('http://specs.openid.net/auth/2.0/');
if (preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) {
if ($type[1] == 'server') {
$result['identifier_select'] = true;
}
preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
if (empty($server)) {
throw new Exception('No servers found!');
}
// Does the server advertise support for either AX or SREG?
$result['ax'] = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>');
$result['sreg'] = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>') || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
$server = $server[1];
if (isset($delegate[2])) {
$result['identity'] = trim($delegate[2]);
}
$result['url'] = $server;
$result['version'] = 2;
return $result;
}
// OpenID 1.1
$ns = preg_quote('http://openid.net/signon/1.1');
if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) {
preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
if (empty($server)) {
throw new Exception('No servers found!');
}
// AX can be used only with OpenID 2.0, so checking only SREG
$result['sreg'] = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>') || strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
$server = $server[1];
if (isset($delegate[1])) {
$result['identity'] = $delegate[1];
}
$result['url'] = $server;
$result['version'] = 1;
return $result;
}
}
$next = true;
$yadis = false;
$url = $originalUrl;
$content = null;
break;
}
if ($next) {
continue;
}
// There are no relevant information in headers, so we search the body.
$content = $this->sendRequest($url, 'GET');
$location = $this->extractHtmlTagValue($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
if ($location) {
$url = $this->buildUrl($url, $location);
continue;
}
}
if (!isset($content)) {
$content = $this->sendRequest($url, 'GET');
}
// At this point, the YADIS Discovery has failed, so we'll switch to openid2 HTML discovery, then fallback to openid 1.1 discovery.
$server = $this->extractHtmlTagValue($content, 'link', 'rel', 'openid2.provider', 'href');
if (!$server) {
// The same with openid 1.1
$server = $this->extractHtmlTagValue($content, 'link', 'rel', 'openid.server', 'href');
$delegate = $this->extractHtmlTagValue($content, 'link', 'rel', 'openid.delegate', 'href');
$version = 1;
} else {
$delegate = $this->extractHtmlTagValue($content, 'link', 'rel', 'openid2.local_id', 'href');
$version = 2;
}
if ($server) {
// We found an OpenID2 OP Endpoint
if ($delegate) {
// We have also found an OP-Local ID.
$result['identity'] = $delegate;
}
$result['url'] = $server;
$result['version'] = $version;
return $result;
}
throw new Exception('No servers found!');
}
throw new Exception('Endless redirection!');
}
Defined in: yii\base\Component::ensureBehaviors()
Makes sure that the behaviors declared in behaviors() are attached to this component.
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Scans content for / tags and extract information from them.
protected string|boolean extractHtmlTagValue ( $content, $tag, $matchAttributeName, $matchAttributeValue, $valueAttributeName ) | ||
$content | string |
HTML content to be be parsed. |
$tag | string |
Name of the source tag. |
$matchAttributeName | string |
Name of the source tag attribute, which should contain $matchAttributeValue |
$matchAttributeValue | string |
Required value of $matchAttributeName |
$valueAttributeName | string |
Name of the source tag attribute, which should contain searched value. |
return | string|boolean |
Searched value, "false" on failure. |
---|
protected function extractHtmlTagValue($content, $tag, $matchAttributeName, $matchAttributeValue, $valueAttributeName)
{
preg_match_all("#<{$tag}[^>]*$matchAttributeName=['\"].*?$matchAttributeValue.*?['\"][^>]*$valueAttributeName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
preg_match_all("#<{$tag}[^>]*$valueAttributeName=['\"](.+?)['\"][^>]*$matchAttributeName=['\"].*?$matchAttributeValue.*?['\"][^>]*/?>#i", $content, $matches2);
$result = array_merge($matches1[1], $matches2[1]);
return empty($result) ? false : $result[0];
}
Gets AX/SREG attributes provided by OP. Should be used only after successful validation.
Note that it does not guarantee that any of the required/optional parameters will be present, or that there will be no other attributes besides those specified. In other words. OP may provide whatever information it wants to. SREG names will be mapped to AX names.
See also https://www.axschema.org/types/.
public array fetchAttributes ( ) | ||
return | array |
Array of attributes with keys being the AX schema names, e.g. 'contact/email' |
---|
public function fetchAttributes()
{
if (isset($this->data['openid_ns']) && $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0') {
// OpenID 2.0
// We search for both AX and SREG attributes, with AX taking precedence.
return array_merge($this->fetchSregAttributes(), $this->fetchAxAttributes());
}
return $this->fetchSregAttributes();
}
Gets AX attributes provided by OP.
protected array fetchAxAttributes ( ) | ||
return | array |
Array of attributes. |
---|
protected function fetchAxAttributes()
{
$alias = null;
if (isset($this->data['openid_ns_ax']) && $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0') {
// It's the most likely case, so we'll check it before
$alias = 'ax';
} else {
// 'ax' prefix is either undefined, or points to another extension, so we search for another prefix
foreach ($this->data as $key => $value) {
if (strncmp($key, 'openid_ns_', 10) === 0 && $value == 'http://openid.net/srv/ax/1.0') {
$alias = substr($key, strlen('openid_ns_'));
break;
}
}
}
if (!$alias) {
// An alias for AX schema has not been found, so there is no AX data in the OP's response
return [];
}
$attributes = [];
foreach ($this->data as $key => $value) {
$keyMatch = 'openid_' . $alias . '_value_';
if (strncmp($key, $keyMatch, strlen($keyMatch))) {
continue;
}
$key = substr($key, strlen($keyMatch));
if (!isset($this->data['openid_' . $alias . '_type_' . $key])) {
/* OP is breaking the spec by returning a field without
associated ns. This shouldn't happen, but it's better
to check, than cause an E_NOTICE.*/
continue;
}
$key = substr($this->data['openid_' . $alias . '_type_' . $key], strlen('http://axschema.org/'));
$attributes[$key] = $value;
}
return $attributes;
}
Gets SREG attributes provided by OP. SREG names will be mapped to AX names.
protected array fetchSregAttributes ( ) | ||
return | array |
Array of attributes with keys being the AX schema names, e.g. 'contact/email' |
---|
protected function fetchSregAttributes()
{
$attributes = [];
$sregToAx = array_flip($this->axToSregMap);
foreach ($this->data as $key => $value) {
$keyMatch = 'openid_sreg_';
if (strncmp($key, $keyMatch, strlen($keyMatch))) {
continue;
}
$key = substr($key, strlen($keyMatch));
if (!isset($sregToAx[$key])) {
// The field name isn't part of the SREG spec, so we ignore it.
continue;
}
$attributes[$sregToAx[$key]] = $value;
}
return $attributes;
}
Defined in: yii\base\Component::getBehavior()
Returns the named behavior object.
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
The behavior name |
return | yii\base\Behavior|null |
The behavior object, or null if the behavior does not exist |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
Returns all behaviors attached to this component.
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
List of behaviors attached to this component |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
public string getClaimedId ( ) | ||
return | string |
Claimed identifier (identity). |
---|
public function getClaimedId()
{
if ($this->_claimedId === null) {
if (isset($this->data['openid_claimed_id'])) {
$this->_claimedId = $this->data['openid_claimed_id'];
} elseif (isset($this->data['openid_identity'])) {
$this->_claimedId = $this->data['openid_identity'];
}
}
return $this->_claimedId;
}
Defined in: yii\authclient\BaseClient::getHttpClient()
Returns HTTP client.
public yii\httpclient\Client getHttpClient ( ) | ||
return | yii\httpclient\Client |
Internal HTTP client. |
---|
public function getHttpClient()
{
if (!is_object($this->_httpClient)) {
$this->_httpClient = $this->createHttpClient($this->_httpClient);
}
return $this->_httpClient;
}
Defined in: yii\authclient\BaseClient::getId()
public string getId ( ) | ||
return | string |
Service id |
---|
public function getId()
{
if (empty($this->_id)) {
$this->_id = $this->getName();
}
return $this->_id;
}
Defined in: yii\authclient\BaseClient::getName()
public string getName ( ) | ||
return | string |
Service name. |
---|
public function getName()
{
if ($this->_name === null) {
$this->_name = $this->defaultName();
}
return $this->_name;
}
public array getNormalizeUserAttributeMap ( ) | ||
return | array |
Normalize user attribute map. |
---|
public function getNormalizeUserAttributeMap()
{
if ($this->_normalizeUserAttributeMap === null) {
$this->_normalizeUserAttributeMap = $this->defaultNormalizeUserAttributeMap();
}
return $this->_normalizeUserAttributeMap;
}
Defined in: yii\authclient\BaseClient::getRequestOptions()
public array getRequestOptions ( ) | ||
return | array |
HTTP request options. |
---|
public function getRequestOptions()
{
return $this->_requestOptions;
}
public string getReturnUrl ( ) | ||
return | string |
Authentication return URL. |
---|
public function getReturnUrl()
{
if ($this->_returnUrl === null) {
$this->_returnUrl = $this->defaultReturnUrl();
}
return $this->_returnUrl;
}
Defined in: yii\authclient\BaseClient::getState()
Returns persistent state value.
protected mixed getState ( $key ) | ||
$key | string |
State key. |
return | mixed |
State value. |
---|
protected function getState($key)
{
return $this->getStateStorage()->get($this->getStateKeyPrefix() . $key);
}
Defined in: yii\authclient\BaseClient::getStateKeyPrefix()
Returns session key prefix, which is used to store internal states.
protected string getStateKeyPrefix ( ) | ||
return | string |
Session key prefix. |
---|
protected function getStateKeyPrefix()
{
return get_class($this) . '_' . $this->getId() . '_';
}
Defined in: yii\authclient\BaseClient::getStateStorage()
public yii\authclient\StateStorageInterface getStateStorage ( ) | ||
return | yii\authclient\StateStorageInterface |
Stage storage. |
---|
public function getStateStorage()
{
if (!is_object($this->_stateStorage)) {
$this->_stateStorage = Yii::createObject($this->_stateStorage);
}
return $this->_stateStorage;
}
Defined in: yii\authclient\BaseClient::getTitle()
public string getTitle ( ) | ||
return | string |
Service title. |
---|
public function getTitle()
{
if ($this->_title === null) {
$this->_title = $this->defaultTitle();
}
return $this->_title;
}
public string getTrustRoot ( ) | ||
return | string |
Client trust root (realm). |
---|
public function getTrustRoot()
{
if ($this->_trustRoot === null) {
$this->_trustRoot = Yii::$app->getRequest()->getHostInfo();
}
return $this->_trustRoot;
}
Defined in: yii\authclient\BaseClient::getUserAttributes()
public array getUserAttributes ( ) | ||
return | array |
List of user attributes |
---|
public function getUserAttributes()
{
if ($this->_userAttributes === null) {
$this->_userAttributes = $this->normalizeUserAttributes($this->initUserAttributes());
}
return $this->_userAttributes;
}
Defined in: yii\authclient\BaseClient::getViewOptions()
public array getViewOptions ( ) | ||
return | array |
View options in format: optionName => optionValue |
---|
public function getViewOptions()
{
if ($this->_viewOptions === null) {
$this->_viewOptions = $this->defaultViewOptions();
}
return $this->_viewOptions;
}
Defined in: yii\base\Component::hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public boolean hasEventHandlers ( $name ) | ||
$name | string |
The event name |
return | boolean |
Whether there is any handler attached to the event. |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkBehaviors | boolean |
Whether to treat behaviors' methods as methods of this component |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Checks if the server specified in the url exists.
public boolean hostExists ( $url ) | ||
$url | string |
URL to check |
return | boolean |
True, if the server exists; false otherwise |
---|
public function hostExists($url)
{
if (strpos($url, '/') === false) {
$server = $url;
} else {
$server = @parse_url($url, PHP_URL_HOST);
}
if (!$server) {
return false;
}
$ips = gethostbynamel($server);
return !empty($ips);
}
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public void init ( ) |
public function init()
{
if ($this->data === null) {
$request = Yii::$app->getRequest();
$this->data = array_merge($request->get(), $request->post()); // OPs may send data as POST or GET.
}
}
Initializes authenticated user attributes.
protected array initUserAttributes ( ) | ||
return | array |
Auth user attributes. |
---|
protected function initUserAttributes()
{
return array_merge(['id' => $this->getClaimedId()], $this->fetchAttributes());
}
Defined in: yii\authclient\BaseClient::normalizeUserAttributes()
Normalize given user attributes according to $normalizeUserAttributeMap.
protected array normalizeUserAttributes ( $attributes ) | ||
$attributes | array |
Raw attributes. |
return | array |
Normalized attributes. |
---|---|---|
throws | yii\base\InvalidConfigException |
on incorrect normalize attribute map. |
protected function normalizeUserAttributes($attributes)
{
foreach ($this->getNormalizeUserAttributeMap() as $normalizedName => $actualName) {
if (is_scalar($actualName)) {
if (array_key_exists($actualName, $attributes)) {
$attributes[$normalizedName] = $attributes[$actualName];
}
} else {
if (is_callable($actualName)) {
$attributes[$normalizedName] = call_user_func($actualName, $attributes);
} elseif (is_array($actualName)) {
$haystack = $attributes;
$searchKeys = $actualName;
$isFound = true;
while (($key = array_shift($searchKeys)) !== null) {
if (is_array($haystack) && array_key_exists($key, $haystack)) {
$haystack = $haystack[$key];
} else {
$isFound = false;
break;
}
}
if ($isFound) {
$attributes[$normalizedName] = $haystack;
}
} else {
throw new InvalidConfigException('Invalid actual name "' . gettype($actualName) . '" specified at "' . get_class($this) . '::normalizeUserAttributeMap"');
}
}
}
return $attributes;
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
This method is the opposite of on().
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
See also on().
public boolean off ( $name, $handler = null ) | ||
$name | string |
Event name |
$handler | callable|null |
The event handler to be removed. If it is null, all handlers attached to the named event will be removed. |
return | boolean |
If a handler is found and detached |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an yii\base\Event object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
The event name |
$handler | callable |
The event handler |
$data | mixed |
The data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data. |
$append | boolean |
Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list. |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
Defined in: yii\authclient\BaseClient::removeState()
Removes persistent state value.
protected boolean removeState ( $key ) | ||
$key | string |
State key. |
return | boolean |
Success. |
---|
protected function removeState($key)
{
return $this->getStateStorage()->remove($this->getStateKeyPrefix() . $key);
}
Sends request to the server
protected array|string sendRequest ( $url, $method = 'GET', $params = [] ) | ||
$url | string |
Request URL. |
$method | string |
Request method. |
$params | array |
Request parameters. |
return | array|string |
Response. |
---|---|---|
throws | yii\base\Exception |
on failure. |
protected function sendRequest($url, $method = 'GET', $params = [])
{
$request = $this->createRequest()
->setMethod($method)
->setUrl($url)
->setData($params);
if ($this->verifyPeer !== null) {
$options = [
'sslVerifyPeer' => $this->verifyPeer
];
if ($this->capath) {
$options['sslCapath'] = $this->capath;
}
if ($this->cainfo) {
$options['sslCafile'] = $this->cainfo;
}
$request->addOptions($options);
}
$response = $request->send();
if ($method == 'HEAD') {
$headers = [];
foreach ($response->getHeaders()->toArray() as $name => $values) {
$headers[strtolower($name)] = array_pop($values);
}
return $headers;
}
return $response->getContent();
}
public void setClaimedId ( $claimedId ) | ||
$claimedId | string |
Claimed identifier (identity). |
public function setClaimedId($claimedId)
{
$this->_claimedId = $claimedId;
}
Defined in: yii\authclient\BaseClient::setHttpClient()
Sets HTTP client to be used.
public void setHttpClient ( $httpClient ) | ||
$httpClient | array|yii\httpclient\Client |
Internal HTTP client. |
public function setHttpClient($httpClient)
{
$this->_httpClient = $httpClient;
}
Defined in: yii\authclient\BaseClient::setId()
public void setId ( $id ) | ||
$id | string |
Service id. |
public function setId($id)
{
$this->_id = $id;
}
Defined in: yii\authclient\BaseClient::setName()
public void setName ( $name ) | ||
$name | string |
Service name. |
public function setName($name)
{
$this->_name = $name;
}
public void setNormalizeUserAttributeMap ( $normalizeUserAttributeMap ) | ||
$normalizeUserAttributeMap | array |
Normalize user attribute map. |
public function setNormalizeUserAttributeMap($normalizeUserAttributeMap)
{
$this->_normalizeUserAttributeMap = $normalizeUserAttributeMap;
}
Defined in: yii\authclient\BaseClient::setRequestOptions()
public void setRequestOptions ( array $options ) | ||
$options | array |
HTTP request options. |
public function setRequestOptions(array $options)
{
$this->_requestOptions = $options;
}
public void setReturnUrl ( $returnUrl ) | ||
$returnUrl | string |
Authentication return URL. |
public function setReturnUrl($returnUrl)
{
$this->_returnUrl = $returnUrl;
}
Defined in: yii\authclient\BaseClient::setState()
Sets persistent state.
protected $this setState ( $key, $value ) | ||
$key | string |
State key. |
$value | mixed |
State value |
return | $this |
The object itself |
---|
protected function setState($key, $value)
{
$this->getStateStorage()->set($this->getStateKeyPrefix() . $key, $value);
return $this;
}
Defined in: yii\authclient\BaseClient::setStateStorage()
public void setStateStorage ( $stateStorage ) | ||
$stateStorage | yii\authclient\StateStorageInterface|array|string |
Stage storage to be used. |
public function setStateStorage($stateStorage)
{
$this->_stateStorage = $stateStorage;
}
Defined in: yii\authclient\BaseClient::setTitle()
public void setTitle ( $title ) | ||
$title | string |
Service title. |
public function setTitle($title)
{
$this->_title = $title;
}
public void setTrustRoot ( $value ) | ||
$value | string |
Client trust root (realm). |
public function setTrustRoot($value)
{
$this->_trustRoot = $value;
}
Defined in: yii\authclient\BaseClient::setUserAttributes()
public void setUserAttributes ( $userAttributes ) | ||
$userAttributes | array |
List of user attributes |
public function setUserAttributes($userAttributes)
{
$this->_userAttributes = $this->normalizeUserAttributes($userAttributes);
}
Defined in: yii\authclient\BaseClient::setViewOptions()
public void setViewOptions ( $viewOptions ) | ||
$viewOptions | array |
View options in format: optionName => optionValue |
public function setViewOptions($viewOptions)
{
$this->_viewOptions = $viewOptions;
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
The event name |
$event | yii\base\Event|null |
The event instance. If not set, a default yii\base\Event object will be created. |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
Performs OpenID verification with the OP.
public boolean validate ( $validateRequiredAttributes = true ) | ||
$validateRequiredAttributes | boolean |
Whether to validate required attributes. |
return | boolean |
Whether the verification was successful. |
---|
public function validate($validateRequiredAttributes = true)
{
$claimedId = $this->getClaimedId();
if (empty($claimedId)) {
return false;
}
$params = [
'openid.assoc_handle' => $this->data['openid_assoc_handle'],
'openid.signed' => $this->data['openid_signed'],
'openid.sig' => $this->data['openid_sig'],
];
if (isset($this->data['openid_ns'])) {
/* We're dealing with an OpenID 2.0 server, so let's set an ns
Even though we should know location of the endpoint,
we still need to verify it by discovery, so $server is not set here*/
$params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
} elseif (isset($this->data['openid_claimed_id']) && $this->data['openid_claimed_id'] != $this->data['openid_identity']) {
// If it's an OpenID 1 provider, and we've got claimed_id,
// we have to append it to the returnUrl, like authUrlV1 does.
$this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $claimedId;
}
if (!$this->compareUrl($this->data['openid_return_to'], $this->returnUrl)) {
// The return_to url must match the url of current request.
return false;
}
$serverInfo = $this->discover($claimedId);
foreach (explode(',', $this->data['openid_signed']) as $item) {
$value = $this->data['openid_' . str_replace('.', '_', $item)];
$params['openid.' . $item] = $value;
}
$params['openid.mode'] = 'check_authentication';
$response = $this->sendRequest($serverInfo['url'], 'POST', $params);
if (preg_match('/is_valid\s*:\s*true/i', $response)) {
if ($validateRequiredAttributes) {
return $this->validateRequiredAttributes();
} else {
return true;
}
} else {
return false;
}
}
Checks if all required attributes are present in the server response.
protected boolean validateRequiredAttributes ( ) | ||
return | boolean |
Whether all required attributes are present. |
---|
protected function validateRequiredAttributes()
{
if (!empty($this->requiredAttributes)) {
$attributes = $this->fetchAttributes();
foreach ($this->requiredAttributes as $openIdAttributeName) {
if (!isset($attributes[$openIdAttributeName])) {
return false;
}
}
}
return true;
}