Class yii\authclient\OpenId

Inheritanceyii\authclient\OpenId » yii\authclient\BaseClient » yii\base\Component
Implementsyii\authclient\ClientInterface
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-authclient/blob/master/src/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 http://openid.net/.

Public Properties

Hide inherited 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
$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

Hide inherited methods

Method Description Defined By
buildAuthUrl() Returns authentication URL. Usually, you want to redirect your user to it. yii\authclient\OpenId
createRequest() Creates HTTP request instance. yii\authclient\BaseClient
discover() Performs Yadis and HTML discovery. yii\authclient\OpenId
fetchAttributes() Gets AX/SREG attributes provided by OP. Should be used only after successful validation. yii\authclient\OpenId
getClaimedId() yii\authclient\OpenId
getHttpClient() Returns HTTP client. yii\authclient\BaseClient
getId() yii\authclient\BaseClient
getName() yii\authclient\BaseClient
getNormalizeUserAttributeMap() yii\authclient\BaseClient
getRequestOptions() yii\authclient\BaseClient
getReturnUrl() yii\authclient\OpenId
getStateStorage() yii\authclient\BaseClient
getTitle() yii\authclient\BaseClient
getTrustRoot() yii\authclient\OpenId
getUserAttributes() yii\authclient\BaseClient
getViewOptions() yii\authclient\BaseClient
hostExists() Checks if the server specified in the url exists. yii\authclient\OpenId
init() yii\authclient\OpenId
setClaimedId() yii\authclient\OpenId
setHttpClient() Sets HTTP client to be used. yii\authclient\BaseClient
setId() yii\authclient\BaseClient
setName() yii\authclient\BaseClient
setNormalizeUserAttributeMap() yii\authclient\BaseClient
setRequestOptions() yii\authclient\BaseClient
setReturnUrl() yii\authclient\OpenId
setStateStorage() yii\authclient\BaseClient
setTitle() yii\authclient\BaseClient
setTrustRoot() yii\authclient\OpenId
setUserAttributes() yii\authclient\BaseClient
setViewOptions() yii\authclient\BaseClient
validate() Performs OpenID verification with the OP. yii\authclient\OpenId

Protected Methods

Hide inherited 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

Hide inherited properties

$authUrl public property

Authentication base URL, which should be used to compose actual authentication URL by buildAuthUrl() method.

public string $authUrl null
$axToSregMap public property

Map of matches between AX and SREG attribute names in format: axAttributeName => sregAttributeName

public array $axToSregMap = [
    
'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',
]
$cainfo public property

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.

public string $cainfo null
$capath public property

Directory that holds multiple CA certificates. This value will take effect only if $verifyPeer is set.

public string $capath null
$claimedId public property

Claimed identifier (identity).

public string $claimedId null
$data public property

Data, which should be used to retrieve the OpenID response. If not set combination of GET and POST will be used.

public array $data null
$optionalAttributes public property

List of attributes, which could be returned from server. Attribute names should be always specified in AX format. For example:

['namePerson/first', 'namePerson/last']
$requiredAttributes public property

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']
$returnUrl public property

Authentication return URL.

public string $returnUrl null
$trustRoot public property

Client trust root (realm).

public string $trustRoot null
$verifyPeer public property

Whether to verify the peer's certificate.

public boolean $verifyPeer null

Method Details

Hide inherited methods

buildAuthUrl() public method

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);
}

            
buildAuthUrlV1() protected method

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, '', '&')]);
}

            
buildAuthUrlV2() protected method

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, '', '&')]);
}

            
buildAxParams() protected method

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

            
buildSregParams() protected method

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

            
buildUrl() protected method

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

            
compareUrl() protected method

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

            
createHttpClient() protected method (available since version 2.1)

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

            
createRequest() public method (available since version 2.1)

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

            
defaultName() protected method

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)));
}

            
defaultNormalizeUserAttributeMap() protected method

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 [];
}

            
defaultRequestOptions() protected method (available since version 2.1)

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,
        'sslVerifyPeer' => false,
    ];
}

            
defaultReturnUrl() protected method

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

            
defaultTitle() protected method

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));
}

            
defaultViewOptions() protected method

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 [];
}

            
discover() public method

Performs Yadis and HTML discovery.

public array discover ( $url )
$url string

Identity URL.

return array

OpenID provider info, following keys will be available:

  • url: string, OP Endpoint (i.e. OpenID provider address).
  • version: int, OpenID protocol version used by provider.
  • identity: string, identity value.
  • identifier_select: bool, whether to request OP to select identity for an user in OpenID 2, does not affect OpenID 1.
  • ax: bool, whether AX attributes should be used.
  • sreg: bool, whether SREG attributes should be used.
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!');
}

            
extractHtmlTagValue() protected method

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];
}

            
fetchAttributes() public method

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 http://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();
}

            
fetchAxAttributes() protected method

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

            
fetchSregAttributes() protected method

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

            
getClaimedId() public method

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

            
getHttpClient() public method (available since version 2.1)

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

            
getId() public method
public string getId ( )
return string

Service id

                public function getId()
{
    if (empty($this->_id)) {
        $this->_id = $this->getName();
    }
    return $this->_id;
}

            
getName() public method
public string getName ( )
return string

Service name.

                public function getName()
{
    if ($this->_name === null) {
        $this->_name = $this->defaultName();
    }
    return $this->_name;
}

            
getNormalizeUserAttributeMap() public method
public array getNormalizeUserAttributeMap ( )
return array

Normalize user attribute map.

                public function getNormalizeUserAttributeMap()
{
    if ($this->_normalizeUserAttributeMap === null) {
        $this->_normalizeUserAttributeMap = $this->defaultNormalizeUserAttributeMap();
    }
    return $this->_normalizeUserAttributeMap;
}

            
getRequestOptions() public method (available since version 2.1)
public array getRequestOptions ( )
return array

HTTP request options.

                public function getRequestOptions()
{
    return $this->_requestOptions;
}

            
getReturnUrl() public method

public string getReturnUrl ( )
return string

Authentication return URL.

                public function getReturnUrl()
{
    if ($this->_returnUrl === null) {
        $this->_returnUrl = $this->defaultReturnUrl();
    }
    return $this->_returnUrl;
}

            
getState() protected method

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);
}

            
getStateKeyPrefix() protected method

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() . '_';
}

            
getStateStorage() public method
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;
}

            
getTitle() public method
public string getTitle ( )
return string

Service title.

                public function getTitle()
{
    if ($this->_title === null) {
        $this->_title = $this->defaultTitle();
    }
    return $this->_title;
}

            
getTrustRoot() public method

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

            
getUserAttributes() public method
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;
}

            
getViewOptions() public method
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;
}

            
hostExists() public method

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);
}

            
init() public method

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.
    }
}

            
initUserAttributes() protected method

Initializes authenticated user attributes.

protected array initUserAttributes ( )
return array

Auth user attributes.

                protected function initUserAttributes()
{
    return array_merge(['id' => $this->getClaimedId()], $this->fetchAttributes());
}

            
normalizeUserAttributes() protected method

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

            
removeState() protected method

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);
}

            
sendRequest() protected method

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

            
setClaimedId() public method

public void setClaimedId ( $claimedId )
$claimedId string

Claimed identifier (identity).

                public function setClaimedId($claimedId)
{
    $this->_claimedId = $claimedId;
}

            
setHttpClient() public method (available since version 2.1)

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

            
setId() public method
public void setId ( $id )
$id string

Service id.

                public function setId($id)
{
    $this->_id = $id;
}

            
setName() public method
public void setName ( $name )
$name string

Service name.

                public function setName($name)
{
    $this->_name = $name;
}

            
setNormalizeUserAttributeMap() public method
public void setNormalizeUserAttributeMap ( $normalizeUserAttributeMap )
$normalizeUserAttributeMap array

Normalize user attribute map.

                public function setNormalizeUserAttributeMap($normalizeUserAttributeMap)
{
    $this->_normalizeUserAttributeMap = $normalizeUserAttributeMap;
}

            
setRequestOptions() public method (available since version 2.1)
public void setRequestOptions ( array $options )
$options array

HTTP request options.

                public function setRequestOptions(array $options)
{
    $this->_requestOptions = $options;
}

            
setReturnUrl() public method

public void setReturnUrl ( $returnUrl )
$returnUrl string

Authentication return URL.

                public function setReturnUrl($returnUrl)
{
    $this->_returnUrl = $returnUrl;
}

            
setState() protected method

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

            
setStateStorage() public method
public void setStateStorage ( $stateStorage )
$stateStorage yii\authclient\StateStorageInterface|array|string

Stage storage to be used.

                public function setStateStorage($stateStorage)
{
    $this->_stateStorage = $stateStorage;
}

            
setTitle() public method
public void setTitle ( $title )
$title string

Service title.

                public function setTitle($title)
{
    $this->_title = $title;
}

            
setTrustRoot() public method

public void setTrustRoot ( $value )
$value string

Client trust root (realm).

                public function setTrustRoot($value)
{
    $this->_trustRoot = $value;
}

            
setUserAttributes() public method
public void setUserAttributes ( $userAttributes )
$userAttributes array

List of user attributes

                public function setUserAttributes($userAttributes)
{
    $this->_userAttributes = $this->normalizeUserAttributes($userAttributes);
}

            
setViewOptions() public method
public void setViewOptions ( $viewOptions )
$viewOptions array

View options in format: optionName => optionValue

                public function setViewOptions($viewOptions)
{
    $this->_viewOptions = $viewOptions;
}

            
validate() public method

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

            
validateRequiredAttributes() protected method

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