From 9ca150bc2c2f4ae1fb82e8d7255ad8f6f9390620 Mon Sep 17 00:00:00 2001 From: phuc vo Date: Fri, 18 Sep 2020 15:50:29 +0700 Subject: [PATCH] support symfony 4 --- .gitignore | 4 +- .gitmodules | 3 - .travis.yml | 6 +- .../RelyingParty/LightOpenIdRelyingParty.php | 18 +- Controller/SecurityController.php | 21 +- DependencyInjection/Configuration.php | 1 - DependencyInjection/FpOpenIdExtension.php | 4 +- .../Security/Factory/OpenIdFactory.php | 8 +- Entity/IdentityManager.php | 15 +- LightOpenId/LightOpenID.php | 1079 +++++++++++++++++ LightOpenId/LightOpenIDProvider.php | 849 +++++++++++++ Model/UserManager.php | 10 +- RelyingParty/AbstractRelyingParty.php | 27 +- RelyingParty/IdentityProviderResponse.php | 3 +- RelyingParty/RecoveredFailureRelyingParty.php | 3 +- RelyingParty/RelyingPartyCollection.php | 6 +- Resources/config/mongodb.xml | 2 +- Resources/config/orm.xml | 2 +- Resources/config/services.xml | 59 +- Resources/views/Security/login.html.twig | 2 +- .../Provider/OpenIdAuthenticationProvider.php | 17 +- .../Core/Authentication/Token/OpenIdToken.php | 22 +- .../Voter/OpenIdAuthenticatedVoter.php | 2 +- Security/Core/User/UserManagerInterface.php | 8 +- .../AbstractOpenIdAuthenticationListener.php | 9 +- .../Firewall/OpenIdAuthenticationListener.php | 4 +- Tests/Functional/app/WebTestCase.php | 2 +- .../Authentication/Token/OpenIdTokenTest.php | 2 +- composer.json | 8 +- 29 files changed, 2066 insertions(+), 130 deletions(-) delete mode 100644 .gitmodules create mode 100644 LightOpenId/LightOpenID.php create mode 100644 LightOpenId/LightOpenIDProvider.php diff --git a/.gitignore b/.gitignore index 525abac..0ee7c83 100644 --- a/.gitignore +++ b/.gitignore @@ -44,4 +44,6 @@ vendor/ Tests/autoload.php Tests/phpunit.xml -bin \ No newline at end of file +bin + +.idea/* diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 9e0379f..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "vendors/LightOpenID"] - path = vendors/LightOpenID - url = git://gitorious.org/lightopenid/lightopenid.git diff --git a/.travis.yml b/.travis.yml index 5c12ddf..24cf44e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,11 +2,9 @@ language: php php: - 5.3 - - 5.4 - - 5.5 - + - 7.0 before_script: composer install --dev notifications: email: - - kotlyar.maksim@gmail.com \ No newline at end of file + - kotlyar.maksim@gmail.com diff --git a/Bridge/RelyingParty/LightOpenIdRelyingParty.php b/Bridge/RelyingParty/LightOpenIdRelyingParty.php index 2563e5c..8ea9b33 100644 --- a/Bridge/RelyingParty/LightOpenIdRelyingParty.php +++ b/Bridge/RelyingParty/LightOpenIdRelyingParty.php @@ -1,13 +1,13 @@ identity, $lightOpenId->getAttributes()); + return new IdentityProviderResponse($lightOpenId->data['openid_identity'], $lightOpenId->getAttributes()); } /** * @param string $trustRoot * - * @return \LightOpenID + * @return LightOpenID + * + * @throws \ErrorException */ protected function createLightOpenID($trustRoot) { - return new \LightOpenID($trustRoot); + return new LightOpenID($trustRoot); } -} \ No newline at end of file +} diff --git a/Controller/SecurityController.php b/Controller/SecurityController.php index e95882e..07a7269 100644 --- a/Controller/SecurityController.php +++ b/Controller/SecurityController.php @@ -1,20 +1,16 @@ container->get('request_stack')->getCurrentRequest(); - /* @var $request \Symfony\Component\HttpFoundation\Request */ $session = $request->getSession(); - /* @var $session \Symfony\Component\HttpFoundation\Session\SessionInterface */ // get the error if any (works with forward and redirect -- see below) if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) { @@ -31,10 +27,9 @@ public function loginAction() $error = $error->getMessage(); } - return $this->container->get('templating')->renderResponse( - 'FpOpenIdBundle:Security:login.html.'.$this->container->getParameter('fp_openid.template.engine'), - array('error' => $error) - ); + return $this->render('FpOpenIdBundle:Security:login.html.twig', [ + 'error' => $error + ]); } public function checkAction() diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index f5b6194..5b09f13 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -8,7 +8,6 @@ class Configuration implements ConfigurationInterface { /** - * * {@inheritDoc} */ public function getConfigTreeBuilder() diff --git a/DependencyInjection/FpOpenIdExtension.php b/DependencyInjection/FpOpenIdExtension.php index 13ba7a7..db25a5f 100644 --- a/DependencyInjection/FpOpenIdExtension.php +++ b/DependencyInjection/FpOpenIdExtension.php @@ -28,7 +28,7 @@ public function load(array $configs, ContainerBuilder $container) /** * @param array $configs - * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container + * @param ContainerBuilder $container * * @throws \InvalidArgumentException */ @@ -65,4 +65,4 @@ protected function loadDbDriver(array $configs, ContainerBuilder $container, $lo $container->setParameter('fp_openid.model.identity.class', $identityClass); } -} \ No newline at end of file +} diff --git a/DependencyInjection/Security/Factory/OpenIdFactory.php b/DependencyInjection/Security/Factory/OpenIdFactory.php index 7dedbf1..9996edd 100644 --- a/DependencyInjection/Security/Factory/OpenIdFactory.php +++ b/DependencyInjection/Security/Factory/OpenIdFactory.php @@ -2,8 +2,8 @@ namespace Fp\OpenIdBundle\DependencyInjection\Security\Factory; use Symfony\Component\Config\Definition\Builder\NodeDefinition; +use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\DefinitionDecorator; use Symfony\Component\DependencyInjection\Reference; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory; @@ -92,7 +92,7 @@ protected function createAuthProvider(ContainerBuilder $container, $id, $config, { $providerId = 'security.authentication.provider.fp_openid.'.$id; $provider = $container - ->setDefinition($providerId, new DefinitionDecorator('security.authentication.provider.fp_openid')) + ->setDefinition($providerId, new ChildDefinition('security.authentication.provider.fp_openid')) ->replaceArgument(0, $id); // with user provider @@ -115,7 +115,7 @@ protected function createEntryPoint($container, $id, $config, $defaultEntryPoint $entryPointId = 'security.authentication.form_entry_point.'.$id; $container - ->setDefinition($entryPointId, new DefinitionDecorator('security.authentication.form_entry_point')) + ->setDefinition($entryPointId, new ChildDefinition('security.authentication.form_entry_point')) ->addArgument(new Reference('security.http_utils')) ->addArgument($config['login_path']) ->addArgument($config['use_forward']) @@ -123,4 +123,4 @@ protected function createEntryPoint($container, $id, $config, $defaultEntryPoint return $entryPointId; } -} \ No newline at end of file +} diff --git a/Entity/IdentityManager.php b/Entity/IdentityManager.php index 86eede9..e5bbf20 100644 --- a/Entity/IdentityManager.php +++ b/Entity/IdentityManager.php @@ -1,18 +1,19 @@ entityManager = $entityManager; $this->identityClass = $identityClass; @@ -55,10 +56,10 @@ public function delete(IdentityInterface $identity) } /** - * @return \Doctrine\ORM\EntityRepository + * @return ObjectRepository */ protected function getIdentityRepository() { return $this->entityManager->getRepository($this->identityClass); } -} \ No newline at end of file +} diff --git a/LightOpenId/LightOpenID.php b/LightOpenId/LightOpenID.php new file mode 100644 index 0000000..301b311 --- /dev/null +++ b/LightOpenId/LightOpenID.php @@ -0,0 +1,1079 @@ += 5.1.2 with cURL or HTTP/HTTPS stream wrappers enabled. + * + * @version v1.3.1 (2016-03-04) + * @link https://code.google.com/p/lightopenid/ Project URL + * @link https://github.com/iignatov/LightOpenID GitHub Repo + * @author Mewp + * @copyright Copyright (c) 2013 Mewp + * @license http://opensource.org/licenses/mit-license.php MIT License + */ +class LightOpenID +{ + public $returnUrl + , $required = array() + , $optional = array() + , $verify_peer = null + , $capath = null + , $cainfo = null + , $cnmatch = null + , $data + , $oauth = array() + , $curl_time_out = 30 // in seconds + , $curl_connect_time_out = 30; // in seconds + private $identity, $claimed_id; + protected $server, $version, $trustRoot, $aliases, $identifier_select = false + , $ax = false, $sreg = false, $setup_url = null, $headers = array() + , $proxy = null, $user_agent = 'LightOpenID' + , $xrds_override_pattern = null, $xrds_override_replacement = null; + static protected $ax_to_sreg = array( + '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', + ); + + function __construct($host, $proxy = null) + { + $this->set_realm($host); + $this->set_proxy($proxy); + + $uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?'); + $this->returnUrl = $this->trustRoot . $uri; + + $this->data = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET; + + if(!function_exists('curl_init') && !in_array('https', stream_get_wrappers())) { + throw new ErrorException('You must have either https wrappers or curl enabled.'); + } + } + + function __isset($name) + { + return in_array($name, array('identity', 'trustRoot', 'realm', 'xrdsOverride', 'mode')); + } + + function __set($name, $value) + { + switch ($name) { + case 'identity': + if (strlen($value = trim((String) $value))) { + if (preg_match('#^xri:/*#i', $value, $m)) { + $value = substr($value, strlen($m[0])); + } elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) { + $value = "http://$value"; + } + if (preg_match('#^https?://[^/]+$#i', $value, $m)) { + $value .= '/'; + } + } + $this->$name = $this->claimed_id = $value; + break; + case 'trustRoot': + case 'realm': + $this->trustRoot = trim($value); + break; + case 'xrdsOverride': + if (is_array($value)) { + list($pattern, $replacement) = $value; + $this->xrds_override_pattern = $pattern; + $this->xrds_override_replacement = $replacement; + } else { + trigger_error('Invalid value specified for "xrdsOverride".', E_USER_ERROR); + } + break; + } + } + + function __get($name) + { + switch ($name) { + case 'identity': + # We return claimed_id instead of identity, + # because the developer should see the claimed identifier, + # i.e. what he set as identity, not the op-local identifier (which is what we verify) + return $this->claimed_id; + case 'trustRoot': + case 'realm': + return $this->trustRoot; + case 'mode': + return empty($this->data['openid_mode']) ? null : $this->data['openid_mode']; + } + } + + function set_proxy($proxy) + { + if (!empty($proxy)) { + // When the proxy is a string - try to parse it. + if (!is_array($proxy)) { + $proxy = parse_url($proxy); + } + + // Check if $proxy is valid after the parsing. + if ($proxy && !empty($proxy['host'])) { + // Make sure that a valid port number is specified. + if (array_key_exists('port', $proxy)) { + if (!is_int($proxy['port'])) { + $proxy['port'] = is_numeric($proxy['port']) ? intval($proxy['port']) : 0; + } + + if ($proxy['port'] <= 0) { + throw new ErrorException('The specified proxy port number is invalid.'); + } + } + + $this->proxy = $proxy; + } + } + } + + /** + * Checks if the server specified in the url exists. + * + * @param $url url to check + * @return true, if the server exists; false otherwise + */ + function hostExists($url) + { + if (strpos($url, '/') === false) { + $server = $url; + } else { + $server = @parse_url($url, PHP_URL_HOST); + } + + if (!$server) { + return false; + } + + return !!gethostbynamel($server); + } + + protected function set_realm($uri) + { + $realm = ''; + + # Set a protocol, if not specified. + $realm .= (($offset = strpos($uri, '://')) === false) ? $this->get_realm_protocol() : ''; + + # Set the offset properly. + $offset = (($offset !== false) ? $offset + 3 : 0); + + # Get only the root, without the path. + $realm .= (($end = strpos($uri, '/', $offset)) === false) ? $uri : substr($uri, 0, $end); + + $this->trustRoot = $realm; + } + + protected function get_realm_protocol() + { + if (!empty($_SERVER['HTTPS'])) { + $use_secure_protocol = ($_SERVER['HTTPS'] != 'off'); + } else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { + $use_secure_protocol = ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'); + } else if (isset($_SERVER['HTTP__WSSC'])) { + $use_secure_protocol = ($_SERVER['HTTP__WSSC'] == 'https'); + } else { + $use_secure_protocol = false; + } + + return $use_secure_protocol ? 'https://' : 'http://'; + } + + protected function request_curl($url, $method='GET', $params=array(), $update_claimed_id) + { + $params = http_build_query($params, '', '&'); + $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : '')); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_HEADER, false); + curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + + if ($method == 'POST') { + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded')); + } else { + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*')); + } + + curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_time_out); // defaults to infinite + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT , $this->curl_connect_time_out); // defaults to 300s + + if (!empty($this->proxy)) { + curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']); + + if (!empty($this->proxy['port'])) { + curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy['port']); + } + + if (!empty($this->proxy['user'])) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']); + } + } + + if($this->verify_peer !== null) { + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer); + if($this->capath) { + curl_setopt($curl, CURLOPT_CAPATH, $this->capath); + } + + if($this->cainfo) { + curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo); + } + } + + if ($method == 'POST') { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $params); + } elseif ($method == 'HEAD') { + curl_setopt($curl, CURLOPT_HEADER, true); + curl_setopt($curl, CURLOPT_NOBODY, true); + } else { + curl_setopt($curl, CURLOPT_HEADER, true); + curl_setopt($curl, CURLOPT_HTTPGET, true); + } + $response = curl_exec($curl); + + if($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) { + curl_setopt($curl, CURLOPT_HTTPGET, true); + $response = curl_exec($curl); + $response = substr($response, 0, strpos($response, "\r\n\r\n")); + } + + if($method == 'HEAD' || $method == 'GET') { + $header_response = $response; + + # If it's a GET request, we want to only parse the header part. + if($method == 'GET') { + $header_response = substr($response, 0, strpos($response, "\r\n\r\n")); + } + + $headers = array(); + foreach(explode("\n", $header_response) as $header) { + $pos = strpos($header,':'); + if ($pos !== false) { + $name = strtolower(trim(substr($header, 0, $pos))); + $headers[$name] = trim(substr($header, $pos+1)); + } + } + + if($update_claimed_id) { + # Update the claimed_id value in case of redirections. + $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); + # Ignore the fragment (some cURL versions don't handle it well). + if (strtok($effective_url, '#') != strtok($url, '#')) { + $this->identity = $this->claimed_id = $effective_url; + } + } + + if($method == 'HEAD') { + return $headers; + } else { + $this->headers = $headers; + } + } + + if (curl_errno($curl)) { + throw new ErrorException(curl_error($curl), curl_errno($curl)); + } + + return $response; + } + + protected function parse_header_array($array, $update_claimed_id) + { + $headers = array(); + foreach($array as $header) { + $pos = strpos($header,':'); + if ($pos !== false) { + $name = strtolower(trim(substr($header, 0, $pos))); + $headers[$name] = trim(substr($header, $pos+1)); + + # Following possible redirections. The point is just to have + # claimed_id change with them, because the redirections + # are followed automatically. + # We ignore redirections with relative paths. + # If any known provider uses them, file a bug report. + if($name == 'location' && $update_claimed_id) { + if(strpos($headers[$name], 'http') === 0) { + $this->identity = $this->claimed_id = $headers[$name]; + } elseif($headers[$name][0] == '/') { + $parsed_url = parse_url($this->claimed_id); + $this->identity = + $this->claimed_id = $parsed_url['scheme'] . '://' + . $parsed_url['host'] + . $headers[$name]; + } + } + } + } + return $headers; + } + + protected function request_streams($url, $method='GET', $params=array(), $update_claimed_id) + { + if(!$this->hostExists($url)) { + throw new ErrorException("Could not connect to $url.", 404); + } + + if (empty($this->cnmatch)) { + $this->cnmatch = parse_url($url, PHP_URL_HOST); + } + + $params = http_build_query($params, '', '&'); + switch($method) { + case 'GET': + $opts = array( + 'http' => array( + 'method' => 'GET', + 'header' => 'Accept: application/xrds+xml, */*', + 'user_agent' => $this->user_agent, + 'ignore_errors' => true, + ), + 'ssl' => array( + 'CN_match' => $this->cnmatch + ) + ); + $url = $url . ($params ? '?' . $params : ''); + if (!empty($this->proxy)) { + $opts['http']['proxy'] = $this->proxy_url(); + } + break; + case 'POST': + $opts = array( + 'http' => array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'user_agent' => $this->user_agent, + 'content' => $params, + 'ignore_errors' => true, + ), + 'ssl' => array( + 'CN_match' => $this->cnmatch + ) + ); + if (!empty($this->proxy)) { + $opts['http']['proxy'] = $this->proxy_url(); + } + break; + case 'HEAD': + // We want to send a HEAD request, but since get_headers() doesn't + // accept $context parameter, we have to change the defaults. + $default = stream_context_get_options(stream_context_get_default()); + + // PHP does not reset all options. Instead, it just sets the options + // available in the passed array, therefore set the defaults manually. + $default += array( + 'http' => array(), + 'ssl' => array() + ); + $default['http'] += array( + 'method' => 'GET', + 'header' => '', + 'user_agent' => '', + 'ignore_errors' => false + ); + $default['ssl'] += array( + 'CN_match' => '' + ); + + $opts = array( + 'http' => array( + 'method' => 'HEAD', + 'header' => 'Accept: application/xrds+xml, */*', + 'user_agent' => $this->user_agent, + 'ignore_errors' => true, + ), + 'ssl' => array( + 'CN_match' => $this->cnmatch + ) + ); + + // Enable validation of the SSL certificates. + if ($this->verify_peer) { + $default['ssl'] += array( + 'verify_peer' => false, + 'capath' => '', + 'cafile' => '' + ); + $opts['ssl'] += array( + 'verify_peer' => true, + 'capath' => $this->capath, + 'cafile' => $this->cainfo + ); + } + + // Change the stream context options. + stream_context_get_default($opts); + + $headers = get_headers($url . ($params ? '?' . $params : '')); + + // Restore the stream context options. + stream_context_get_default($default); + + if (!empty($headers)) { + if (intval(substr($headers[0], strlen('HTTP/1.1 '))) == 405) { + // The server doesn't support HEAD - emulate it with a GET. + $args = func_get_args(); + $args[1] = 'GET'; + call_user_func_array(array($this, 'request_streams'), $args); + $headers = $this->headers; + } else { + $headers = $this->parse_header_array($headers, $update_claimed_id); + } + } else { + $headers = array(); + } + + return $headers; + } + + if ($this->verify_peer) { + $opts['ssl'] += array( + 'verify_peer' => true, + 'capath' => $this->capath, + 'cafile' => $this->cainfo + ); + } + + $context = stream_context_create ($opts); + $data = file_get_contents($url, false, $context); + # This is a hack for providers who don't support HEAD requests. + # It just creates the headers array for the last request in $this->headers. + if(isset($http_response_header)) { + $this->headers = $this->parse_header_array($http_response_header, $update_claimed_id); + } + + return $data; + } + + protected function request($url, $method='GET', $params=array(), $update_claimed_id=false) + { + $use_curl = false; + + if (function_exists('curl_init')) { + if (!$use_curl) { + # When allow_url_fopen is disabled, PHP streams will not work. + $use_curl = !ini_get('allow_url_fopen'); + } + + if (!$use_curl) { + # When there is no HTTPS wrapper, PHP streams cannott be used. + $use_curl = !in_array('https', stream_get_wrappers()); + } + + if (!$use_curl) { + # With open_basedir or safe_mode set, cURL can't follow redirects. + $use_curl = !(ini_get('safe_mode') || ini_get('open_basedir')); + } + } + + return + $use_curl + ? $this->request_curl($url, $method, $params, $update_claimed_id) + : $this->request_streams($url, $method, $params, $update_claimed_id); + } + + protected function proxy_url() + { + $result = ''; + + if (!empty($this->proxy)) { + $result = $this->proxy['host']; + + if (!empty($this->proxy['port'])) { + $result = $result . ':' . $this->proxy['port']; + } + + if (!empty($this->proxy['user'])) { + $result = $this->proxy['user'] . ':' . $this->proxy['pass'] . '@' . $result; + } + + $result = 'http://' . $result; + } + + return $result; + } + + protected function build_url($url, $parts) + { + if (isset($url['query'], $parts['query'])) { + $parts['query'] = $url['query'] . '&' . $parts['query']; + } + + $url = $parts + $url; + $url = $url['scheme'] . '://' + . (empty($url['username'])?'' + :(empty($url['password'])? "{$url['username']}@" + :"{$url['username']}:{$url['password']}@")) + . $url['host'] + . (empty($url['port'])?'':":{$url['port']}") + . (empty($url['path'])?'':$url['path']) + . (empty($url['query'])?'':"?{$url['query']}") + . (empty($url['fragment'])?'':"#{$url['fragment']}"); + return $url; + } + + /** + * Helper function used to scan for / tags and extract information + * from them + */ + protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName) + { + preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1); + preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2); + + $result = array_merge($matches1[1], $matches2[1]); + return empty($result)?false:$result[0]; + } + + /** + * Performs Yadis and HTML discovery. Normally not used. + * @param $url Identity URL. + * @return String OP Endpoint (i.e. OpenID provider address). + * @throws ErrorException + */ + function discover($url) + { + if (!$url) throw new ErrorException('No identity supplied.'); + # 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; + + # Allows optional regex replacement of the URL, e.g. to use Google Apps + # as an OpenID provider without setting up XRDS on the domain hosting. + if (!is_null($this->xrds_override_pattern) && !is_null($this->xrds_override_replacement)) { + $url = preg_replace($this->xrds_override_pattern, $this->xrds_override_replacement, $url); + } + + # We'll jump a maximum of 5 times, to avoid endless redirections. + for ($i = 0; $i < 5; $i ++) { + if ($yadis) { + $headers = $this->request($url, 'HEAD', array(), true); + + $next = false; + if (isset($headers['x-xrds-location'])) { + $url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location']))); + $next = true; + } + + if (isset($headers['content-type']) && $this->is_allowed_type($headers['content-type'])) { + # Found an XRDS document, now let's find the server, and optionally delegate. + $content = $this->request($url, 'GET'); + + preg_match_all('#(.*?)#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('#\s*'.$ns.'(server|signon)\s*#s', $content, $type)) { + if ($type[1] == 'server') $this->identifier_select = true; + + preg_match('#(.*)#', $content, $server); + preg_match('#<(Local|Canonical)ID>(.*)#', $content, $delegate); + if (empty($server)) { + return false; + } + # Does the server advertise support for either AX or SREG? + $this->ax = (bool) strpos($content, 'http://openid.net/srv/ax/1.0'); + $this->sreg = strpos($content, 'http://openid.net/sreg/1.0') + || strpos($content, 'http://openid.net/extensions/sreg/1.1'); + + $server = $server[1]; + if (isset($delegate[2])) $this->identity = trim($delegate[2]); + $this->version = 2; + + $this->server = $server; + return $server; + } + + # OpenID 1.1 + $ns = preg_quote('http://openid.net/signon/1.1', '#'); + if (preg_match('#\s*'.$ns.'\s*#s', $content)) { + + preg_match('#(.*)#', $content, $server); + preg_match('#<.*?Delegate>(.*)#', $content, $delegate); + if (empty($server)) { + return false; + } + # AX can be used only with OpenID 2.0, so checking only SREG + $this->sreg = strpos($content, 'http://openid.net/sreg/1.0') + || strpos($content, 'http://openid.net/extensions/sreg/1.1'); + + $server = $server[1]; + if (isset($delegate[1])) $this->identity = $delegate[1]; + $this->version = 1; + + $this->server = $server; + return $server; + } + } + + $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->request($url, 'GET', array(), true); + + if (isset($this->headers['x-xrds-location'])) { + $url = $this->build_url(parse_url($url), parse_url(trim($this->headers['x-xrds-location']))); + continue; + } + + $location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content'); + if ($location) { + $url = $this->build_url(parse_url($url), parse_url($location)); + continue; + } + } + + if (!$content) $content = $this->request($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->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href'); + $delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href'); + $this->version = 2; + + if (!$server) { + # The same with openid 1.1 + $server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href'); + $delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href'); + $this->version = 1; + } + + if ($server) { + # We found an OpenID2 OP Endpoint + if ($delegate) { + # We have also found an OP-Local ID. + $this->identity = $delegate; + } + $this->server = $server; + return $server; + } + + throw new ErrorException("No OpenID Server found at $url", 404); + } + throw new ErrorException('Endless redirection!', 500); + } + + protected function is_allowed_type($content_type) { + # Apparently, some providers return XRDS documents as text/html. + # While it is against the spec, allowing this here shouldn't break + # compatibility with anything. + $allowed_types = array('application/xrds+xml', 'text/xml'); + + # Only allow text/html content type for the Yahoo logins, since + # it might cause an endless redirection for the other providers. + if ($this->get_provider_name($this->claimed_id) == 'yahoo') { + $allowed_types[] = 'text/html'; + } + + foreach ($allowed_types as $type) { + if (strpos($content_type, $type) !== false) { + return true; + } + } + + return false; + } + + protected function get_provider_name($provider_url) { + $result = ''; + + if (!empty($provider_url)) { + $tokens = array_reverse( + explode('.', parse_url($provider_url, PHP_URL_HOST)) + ); + $result = strtolower( + (count($tokens) > 1 && strlen($tokens[1]) > 3) + ? $tokens[1] + : (count($tokens) > 2 ? $tokens[2] : '') + ); + } + + return $result; + } + + protected function sregParams() + { + $params = array(); + # 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 ($this->required) { + $params['openid.sreg.required'] = array(); + foreach ($this->required as $required) { + if (!isset(self::$ax_to_sreg[$required])) continue; + $params['openid.sreg.required'][] = self::$ax_to_sreg[$required]; + } + $params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']); + } + + if ($this->optional) { + $params['openid.sreg.optional'] = array(); + foreach ($this->optional as $optional) { + if (!isset(self::$ax_to_sreg[$optional])) continue; + $params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional]; + } + $params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']); + } + return $params; + } + + protected function axParams() + { + $params = array(); + if ($this->required || $this->optional) { + $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0'; + $params['openid.ax.mode'] = 'fetch_request'; + $this->aliases = array(); + $counts = array(); + $required = array(); + $optional = array(); + foreach (array('required','optional') as $type) { + foreach ($this->$type as $alias => $field) { + if (is_int($alias)) $alias = strtr($field, '/', '_'); + $this->aliases[$alias] = 'http://axschema.org/' . $field; + if (empty($counts[$alias])) $counts[$alias] = 0; + $counts[$alias] += 1; + ${$type}[] = $alias; + } + } + foreach ($this->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($required) { + $params['openid.ax.required'] = implode(',', $required); + } + if($optional) { + $params['openid.ax.if_available'] = implode(',', $optional); + } + } + return $params; + } + + protected function authUrl_v1($immediate) + { + $returnUrl = $this->returnUrl; + # 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($this->identity != $this->claimed_id) { + $returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id; + } + + $params = array( + 'openid.return_to' => $returnUrl, + 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup', + 'openid.identity' => $this->identity, + 'openid.trust_root' => $this->trustRoot, + ) + $this->sregParams(); + + return $this->build_url(parse_url($this->server) + , array('query' => http_build_query($params, '', '&'))); + } + + protected function authUrl_v2($immediate) + { + $params = array( + 'openid.ns' => 'http://specs.openid.net/auth/2.0', + 'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup', + 'openid.return_to' => $this->returnUrl, + 'openid.realm' => $this->trustRoot, + ); + + if ($this->ax) { + $params += $this->axParams(); + } + + if ($this->sreg) { + $params += $this->sregParams(); + } + + if (!$this->ax && !$this->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 += $this->axParams() + $this->sregParams(); + } + + if (!empty($this->oauth) && is_array($this->oauth)) { + $params['openid.ns.oauth'] = 'http://specs.openid.net/extensions/oauth/1.0'; + $params['openid.oauth.consumer'] = str_replace(array('http://', 'https://'), '', $this->trustRoot); + $params['openid.oauth.scope'] = implode(' ', $this->oauth); + } + + if ($this->identifier_select) { + $params['openid.identity'] = $params['openid.claimed_id'] + = 'http://specs.openid.net/auth/2.0/identifier_select'; + } else { + $params['openid.identity'] = $this->identity; + $params['openid.claimed_id'] = $this->claimed_id; + } + + return $this->build_url(parse_url($this->server) + , array('query' => http_build_query($params, '', '&'))); + } + + /** + * Returns authentication url. Usually, you want to redirect your user to it. + * @return String The authentication url. + * @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1. + * @throws ErrorException + */ + function authUrl($immediate = false) + { + if ($this->setup_url && !$immediate) return $this->setup_url; + if (!$this->server) $this->discover($this->identity); + + if ($this->version == 2) { + return $this->authUrl_v2($immediate); + } + return $this->authUrl_v1($immediate); + } + + /** + * Performs OpenID verification with the OP. + * @return Bool Whether the verification was successful. + * @throws ErrorException + */ + function validate() + { + # If the request was using immediate mode, a failure may be reported + # by presenting user_setup_url (for 1.1) or reporting + # mode 'setup_needed' (for 2.0). Also catching all modes other than + # id_res, in order to avoid throwing errors. + if(isset($this->data['openid_user_setup_url'])) { + $this->setup_url = $this->data['openid_user_setup_url']; + return false; + } + if($this->mode != 'id_res') { + return false; + } + + $this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity']; + $params = array( + '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 authUrl_v1 does. + $this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?') + . 'openid.claimed_id=' . $this->claimed_id; + } + + if ($this->data['openid_return_to'] != $this->returnUrl) { + # The return_to url must match the url of current request. + # I'm assuming that no one will set the returnUrl to something that doesn't make sense. + return false; + } + + $server = $this->discover($this->claimed_id); + + foreach (explode(',', $this->data['openid_signed']) as $item) { + # Checking whether magic_quotes_gpc is turned on, because + # the function may fail if it is. For example, when fetching + # AX namePerson, it might contain an apostrophe, which will be escaped. + # In such case, validation would fail, since we'd send different data than OP + # wants to verify. stripslashes() should solve that problem, but we can't + # use it when magic_quotes is off. + $value = $this->data['openid_' . str_replace('.','_',$item)]; + $params['openid.' . $item] = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() ? stripslashes($value) : $value; + + } + + $params['openid.mode'] = 'check_authentication'; + + $response = $this->request($server, 'POST', $params); + + return preg_match('/is_valid\s*:\s*true/i', $response); + } + + protected function getAxAttributes() + { + $result = array(); + + if ($alias = $this->getNamespaceAlias('http://openid.net/srv/ax/1.0', 'ax')) { + $prefix = 'openid_' . $alias; + $length = strlen('http://axschema.org/'); + + foreach (explode(',', $this->data['openid_signed']) as $key) { + $keyMatch = $alias . '.type.'; + + if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) { + continue; + } + + $key = substr($key, strlen($keyMatch)); + $idv = $prefix . '_value_' . $key; + $idc = $prefix . '_count_' . $key; + $key = substr($this->getItem($prefix . '_type_' . $key), $length); + + if (!empty($key)) { + if (($count = intval($this->getItem($idc))) > 0) { + $value = array(); + + for ($i = 1; $i <= $count; $i++) { + $value[] = $this->getItem($idv . '_' . $i); + } + + $value = ($count == 1) ? reset($value) : $value; + } else { + $value = $this->getItem($idv); + } + + if (!is_null($value)) { + $result[$key] = $value; + } + } + } + } else { + // No alias for the AX schema has been found, + // so there is no AX data in the OP's response. + } + + return $result; + } + + protected function getSregAttributes() + { + $attributes = array(); + $sreg_to_ax = array_flip(self::$ax_to_sreg); + foreach (explode(',', $this->data['openid_signed']) as $key) { + $keyMatch = 'sreg.'; + if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) { + continue; + } + $key = substr($key, strlen($keyMatch)); + if (!isset($sreg_to_ax[$key])) { + # The field name isn't part of the SREG spec, so we ignore it. + continue; + } + $attributes[$sreg_to_ax[$key]] = $this->data['openid_sreg_' . $key]; + } + return $attributes; + } + + /** + * 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. + * * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email' + * @see http://www.axschema.org/types/ + */ + function getAttributes() + { + 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 $this->getAxAttributes() + $this->getSregAttributes(); + } + return $this->getSregAttributes(); + } + + /** + * Gets an OAuth request token if the OpenID+OAuth hybrid protocol has been used. + * + * In order to use the OpenID+OAuth hybrid protocol, you need to add at least one + * scope to the $openid->oauth array before you get the call to getAuthUrl(), e.g.: + * $openid->oauth[] = 'https://www.googleapis.com/auth/plus.me'; + * + * Furthermore the registered consumer name must fit the OpenID realm. + * To register an OpenID consumer at Google use: https://www.google.com/accounts/ManageDomains + * + * @return string|bool OAuth request token on success, FALSE if no token was provided. + */ + function getOAuthRequestToken() + { + $alias = $this->getNamespaceAlias('http://specs.openid.net/extensions/oauth/1.0'); + + return !empty($alias) ? $this->data['openid_' . $alias . '_request_token'] : false; + } + + /** + * Gets the alias for the specified namespace, if it's present. + * + * @param string $namespace The namespace for which an alias is needed. + * @param string $hint Common alias of this namespace, used for optimization. + * @return string|null The namespace alias if found, otherwise - NULL. + */ + private function getNamespaceAlias($namespace, $hint = null) + { + $result = null; + + if (empty($hint) || $this->getItem('openid_ns_' . $hint) != $namespace) { + // The common alias is either undefined or points to + // some other extension - search for another alias.. + $prefix = 'openid_ns_'; + $length = strlen($prefix); + + foreach ($this->data as $key => $val) { + if (strncmp($key, $prefix, $length) === 0 && $val === $namespace) { + $result = trim(substr($key, $length)); + break; + } + } + } else { + $result = $hint; + } + + return $result; + } + + /** + * Gets an item from the $data array by the specified id. + * + * @param string $id The id of the desired item. + * @return string|null The item if found, otherwise - NULL. + */ + private function getItem($id) + { + return isset($this->data[$id]) ? $this->data[$id] : null; + } +} diff --git a/LightOpenId/LightOpenIDProvider.php b/LightOpenId/LightOpenIDProvider.php new file mode 100644 index 0000000..60db78b --- /dev/null +++ b/LightOpenId/LightOpenIDProvider.php @@ -0,0 +1,849 @@ += 5.1.2 + * + * This is an alpha version, using it in production code is not recommended, + * until you are *sure* that it works and is secure. + * + * Please send me messages about your testing results + * (even if successful, so I know that it has been tested). + * Also, if you think there's a way to make it easier to use, tell me -- it's an alpha for a reason. + * Same thing applies to bugs in code, suggestions, + * and everything else you'd like to say about the library. + * + * There's no usage documentation here, see the examples. + * + * @author Mewp + * @copyright Copyright (c) 2010, Mewp + * @license http://www.opensource.org/licenses/mit-license.php MIT + */ +ini_set('error_log','log'); +abstract class LightOpenIDProvider +{ + # URL-s to XRDS and server location. + public $xrdsLocation, $serverLocation; + + # Should we operate in server, or signon mode? + public $select_id = false; + + # Lifetime of an association. + protected $assoc_lifetime = 600; + + # Variables below are either set automatically, or are constant. + # ----- + # Can we support DH? + protected $dh = true; + protected $ns = 'http://specs.openid.net/auth/2.0'; + protected $data, $assoc; + + # Default DH parameters as defined in the specification. + protected $default_modulus; + protected $default_gen = 'Ag=='; + + # AX <-> SREG transform + protected $ax_to_sreg = array( + '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', + ); + + # Math + private $add, $mul, $pow, $mod, $div, $powmod; + # ----- + + # ------------------------------------------------------------------------ # + # Functions you probably want to implement when extending the class. + + /** + * Checks whether an user is authenticated. + * The function should determine what fields it wants to send to the RP, + * and put them in the $attributes array. + * @param Array $attributes + * @param String $realm Realm used for authentication. + * @return String OP-local identifier of an authenticated user, or an empty value. + */ + abstract function checkid($realm, &$attributes); + + /** + * Displays an user interface for inputting user's login and password. + * Attributes are always AX field namespaces, with stripped host part. + * For example, the $attributes array may be: + * array( 'required' => array('namePerson/friendly', 'contact/email'), + * 'optional' => array('pref/timezone', 'pref/language') + * @param String $identity Discovered identity string. May be used to extract login, unless using $this->select_id + * @param String $realm Realm used for authentication. + * @param String Association handle. must be sent as openid.assoc_handle in $_GET or $_POST in subsequent requests. + * @param Array User attributes requested by the RP. + */ + abstract function setup($identity, $realm, $assoc_handle, $attributes); + + /** + * Stores an association. + * If you want to use php sessions in your provider code, you have to replace it. + * @param String $handle Association handle -- should be used as a key. + * @param Array $assoc Association data. + */ + protected function setAssoc($handle, $assoc) + { + $oldSession = session_id(); + session_commit(); + session_id($assoc['handle']); + session_start(); + $_SESSION['assoc'] = $assoc; + session_commit(); + if($oldSession) { + session_id($oldSession); + session_start(); + } + } + + /** + * Retreives association data. + * If you want to use php sessions in your provider code, you have to replace it. + * @param String $handle Association handle. + * @return Array Association data. + */ + protected function getAssoc($handle) + { + $oldSession = session_id(); + session_commit(); + session_id($handle); + session_start(); + $assoc = null; + if(!empty($_SESSION['assoc'])) { + $assoc = $_SESSION['assoc']; + } + session_commit(); + if($oldSession) { + session_id($oldSession); + session_start(); + } + return $assoc; + } + + /** + * Deletes an association. + * If you want to use php sessions in your provider code, you have to replace it. + * @param String $handle Association handle. + */ + protected function delAssoc($handle) + { + $oldSession = session_id(); + session_commit(); + session_id($handle); + session_start(); + session_destroy(); + if($oldSession) { + session_id($oldSession); + session_start(); + } + } + + # ------------------------------------------------------------------------ # + # Functions that you might want to implement. + + /** + * Redirects the user to an url. + * @param String $location The url that the user will be redirected to. + */ + protected function redirect($location) + { + header('Location: ' . $location); + die(); + } + + /** + * Generates a new association handle. + * @return string + */ + protected function assoc_handle() + { + return sha1(microtime()); + } + + /** + * Generates a random shared secret. + * @return string + */ + protected function shared_secret($hash) + { + $length = 20; + if($hash == 'sha256') { + $length = 256; + } + + $secret = ''; + for($i = 0; $i < $length; $i++) { + $secret .= mt_rand(0,255); + } + + return $secret; + } + + /** + * Generates a private key. + * @param int $length Length of the key. + */ + protected function keygen($length) + { + $key = ''; + for($i = 1; $i < $length; $i++) { + $key .= mt_rand(0,9); + } + $key .= mt_rand(1,9); + + return $key; + } + + # ------------------------------------------------------------------------ # + # Functions that you probably shouldn't touch. + + function __construct() + { + $this->default_modulus = + 'ANz5OguIOXLsDhmYmsWizjEOHTdxfo2Vcbt2I3MYZuYe91ouJ4mLBX+YkcLiemOcPy' + . 'm2CBRYHNOyyjmG0mg3BVd9RcLn5S3IHHoXGHblzqdLFEi/368Ygo79JRnxTkXjgmY0' + . 'rxlJ5bU1zIKaSDuKdiI+XUkKJX8Fvf8W8vsixYOr'; + + $location = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' + . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; + $location = preg_replace('/\?.*/','',$location); + $this->serverLocation = $location; + $location .= (strpos($location, '?') ? '&' : '?') . 'xrds'; + $this->xrdsLocation = $location; + + $this->data = $_GET + $_POST; + + # We choose GMP if avaiable, and bcmath otherwise + if(function_exists('gmp_add')) { + $this->add = 'gmp_add'; + $this->mul = 'gmp_mul'; + $this->pow = 'gmp_pow'; + $this->mod = 'gmp_mod'; + $this->div = 'gmp_div'; + $this->powmod = 'gmp_powm'; + } elseif(function_exists('bcadd')) { + $this->add = 'bcadd'; + $this->mul = 'bcmul'; + $this->pow = 'bcpow'; + $this->mod = 'bcmod'; + $this->div = 'bcdiv'; + $this->powmod = 'bcpowmod'; + } else { + # If neither are avaiable, we can't use DH + $this->dh = false; + } + + # However, we do require the hash functions. + # They should be built-in anyway. + if(!function_exists('hash_algos')) { + $this->dh = false; + } + } + + /** + * Displays an XRDS document, or redirects to it. + * By default, it detects whether it should display or redirect automatically. + * @param bool|null $force When true, always display the document, when false always redirect. + */ + function xrds($force=null) + { + if($force) { + echo $this->xrdsContent(); + die(); + } elseif($force === false) { + header('X-XRDS-Location: '. $this->xrdsLocation); + return; + } + + if (isset($_GET['xrds']) + || (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xrds+xml') !== false) + ) { + header('Content-Type: application/xrds+xml'); + echo $this->xrdsContent(); + die(); + } + + header('X-XRDS-Location: ' . $this->xrdsLocation); + } + + /** + * Returns the content of the XRDS document + * @return String The XRDS document. + */ + protected function xrdsContent() + { + $lines = array( + '', + '', + '', + ' ', + ' ' . $this->ns . '/' . ($this->select_id ? 'server' : 'signon') .'', + ' ' . $this->serverLocation . '', + ' ', + '', + '' + ); + return implode("\n", $lines); + } + + /** + * Does everything that a provider has to -- in one function. + */ + function server() + { + if(isset($this->data['openid_assoc_handle'])) { + $this->assoc = $this->getAssoc($this->data['openid_assoc_handle']); + if(isset($this->assoc['data'])) { + # We have additional data stored for setup. + $this->data += $this->assoc['data']; + unset($this->assoc['data']); + } + } + + if (isset($this->data['openid_ns']) + && $this->data['openid_ns'] == $this->ns + ) { + if(!isset($this->data['openid_mode'])) $this->errorResponse(); + + switch($this->data['openid_mode']) + { + case 'checkid_immediate': + case 'checkid_setup': + $this->checkRealm(); + # We support AX xor SREG. + $attributes = $this->ax(); + if(!$attributes) { + $attributes = $this->sreg(); + } + + # Even if some user is authenticated, we need to know if it's + # the same one that want's to authenticate. + # Of course, if we use select_id, we accept any user. + if (($identity = $this->checkid($this->data['openid_realm'], $attrValues)) + && ($this->select_id || $identity == $this->data['openid_identity']) + ) { + $this->positiveResponse($identity, $attrValues); + } elseif($this->data['openid_mode'] == 'checkid_immediate') { + $this->redirect($this->response(array('openid.mode' => 'setup_needed'))); + } else { + if(!$this->assoc) { + $this->generateAssociation(); + $this->assoc['private'] = true; + } + $this->assoc['data'] = $this->data; + $this->setAssoc($this->assoc['handle'], $this->assoc); + $this->setup($this->data['openid_identity'], + $this->data['openid_realm'], + $this->assoc['handle'], + $attributes); + } + break; + case 'associate': + $this->associate(); + break; + case 'check_authentication': + $this->checkRealm(); + if($this->verify()) { + echo "ns:$this->ns\nis_valid:true"; + if(strpos($this->data['openid_signed'],'invalidate_handle') !== false) { + echo "\ninvalidate_handle:" . $this->data['openid_invalidate_handle']; + } + } else { + echo "ns:$this->ns\nis_valid:false"; + } + die(); + break; + default: + $this->errorResponse(); + } + } else { + $this->xrds(); + } + } + + protected function checkRealm() + { + if (!isset($this->data['openid_return_to'], $this->data['openid_realm'])) { + $this->errorResponse(); + } + + $realm = str_replace('\*', '[^/]', preg_quote($this->data['openid_realm'])); + if(!preg_match("#^$realm#", $this->data['openid_return_to'])) { + $this->errorResponse(); + } + } + + protected function ax() + { + # Namespace prefix that the fields must have. + $ns = 'http://axschema.org/'; + + # First, we must find out what alias is used for AX. + # Let's check the most likely one + $alias = null; + if (isset($this->data['openid_ns_ax']) + && $this->data['openid_ns_ax'] == 'http://openid.net/srv/ax/1.0' + ) { + $alias = 'ax'; + } else { + foreach($this->data as $name => $value) { + if ($value == 'http://openid.net/srv/ax/1.0' + && preg_match('/openid_ns_(.+)/', $name, $m) + ) { + $alias = $m[1]; + break; + } + } + } + + if(!$alias) { + return null; + } + + $fields = array(); + # Now, we must search again, this time for field aliases + foreach($this->data as $name => $value) { + if (strpos($name, 'openid_' . $alias . '_type') === false + || strpos($value, $ns) === false) { + continue; + } + + $name = substr($name, strlen('openid_' . $alias . '_type_')); + $value = substr($value, strlen($ns)); + + $fields[$name] = $value; + } + + # Then, we find out what fields are required and optional + $required = array(); + $if_available = array(); + foreach(array('required','if_available') as $type) { + if(empty($this->data["openid_{$alias}_{$type}"])) { + continue; + } + $attributes = explode(',', $this->data["openid_{$alias}_{$type}"]); + foreach($attributes as $attr) { + if(empty($fields[$attr])) { + # There is an undefined field here, so we ignore it. + continue; + } + + ${$type}[] = $fields[$attr]; + } + } + + $this->data['ax'] = true; + return array('required' => $required, 'optional' => $if_available); + } + + protected function sreg() + { + $sreg_to_ax = array_flip($this->ax_to_sreg); + + $attributes = array('required' => array(), 'optional' => array()); + + if (empty($this->data['openid_sreg_required']) + && empty($this->data['openid_sreg_optional']) + ) { + return $attributes; + } + + foreach(array('required', 'optional') as $type) { + foreach(explode(',',$this->data['openid_sreg_' . $type]) as $attr) { + if(empty($sreg_to_ax[$attr])) { + # Undefined attribute in SREG request. + # Shouldn't happen, but we check anyway. + continue; + } + + $attributes[$type][] = $sreg_to_ax[$attr]; + } + } + + return $attributes; + } + + /** + * Aids an RP in assertion verification. + * @return bool Information whether the verification suceeded. + */ + protected function verify() + { + # Firstly, we need to make sure that there's an association. + # Otherwise the verification will fail, + # because we've signed assoc_handle in the assertion + if(empty($this->assoc)) { + return false; + } + + # Next, we check that it's a private association, + # i.e. one made without RP input. + # Otherwise, the RP shouldn't ask us to verify. + if(empty($this->assoc['private'])) { + return false; + } + + # Now we have to check if the nonce is correct, to prevent replay attacks. + if($this->data['openid_response_nonce'] != $this->assoc['nonce']) { + return false; + } + + # Getting the signed fields for signature. + $sig = array(); + $signed = explode(',', $this->data['openid_signed']); + foreach($signed as $field) { + $name = strtr($field, '.', '_'); + if(!isset($this->data['openid_' . $name])) { + return false; + } + + $sig[$field] = $this->data['openid_' . $name]; + } + + # Computing the signature and checking if it matches. + $sig = $this->keyValueForm($sig); + if ($this->data['openid_sig'] != + base64_encode(hash_hmac($this->assoc['hash'], $sig, $this->assoc['mac'], true)) + ) { + return false; + } + + # Clearing the nonce, so that it won't be used again. + $this->assoc['nonce'] = null; + + if(empty($this->assoc['private'])) { + # Commiting changes to the association. + $this->setAssoc($this->assoc['handle'], $this->assoc); + } else { + # Private associations shouldn't be used again, se we can as well delete them. + $this->delAssoc($this->assoc['handle']); + } + + # Nothing has failed, so the verification was a success. + return true; + } + + /** + * Performs association with an RP. + */ + protected function associate() + { + # Rejecting no-encryption without TLS. + if(empty($_SERVER['HTTPS']) && $this->data['openid_session_type'] == 'no-encryption') { + $this->directErrorResponse(); + } + + # Checking whether we support DH at all. + if (!$this->dh && substr($this->data['openid_session_type'], 0, 2) == 'DH') { + $this->redirect($this->response(array( + 'openid.error' => 'DH not supported', + 'openid.error_code' => 'unsupported-type', + 'openid.session_type' => 'no-encryption' + ))); + } + + # Creating the association + $this->assoc = array(); + $this->assoc['hash'] = $this->data['openid_assoc_type'] == 'HMAC-SHA256' ? 'sha256' : 'sha1'; + $this->assoc['handle'] = $this->assoc_handle(); + + # Getting the shared secret + if($this->data['openid_session_type'] == 'no-encryption') { + $this->assoc['mac'] = base64_encode($this->shared_secret($this->assoc['hash'])); + } else { + $this->dh(); + } + + # Preparing the direct response... + $response = array( + 'ns' => $this->ns, + 'assoc_handle' => $this->assoc['handle'], + 'assoc_type' => $this->data['openid_assoc_type'], + 'session_type' => $this->data['openid_session_type'], + 'expires_in' => $this->assoc_lifetime + ); + + if(isset($this->assoc['dh_server_public'])) { + $response['dh_server_public'] = $this->assoc['dh_server_public']; + $response['enc_mac_key'] = $this->assoc['mac']; + } else { + $response['mac_key'] = $this->assoc['mac']; + } + + # ...and sending it. + echo $this->keyValueForm($response); + die(); + } + + /** + * Creates a private association. + */ + protected function generateAssociation() + { + $this->assoc = array(); + # We use sha1 by default. + $this->assoc['hash'] = 'sha1'; + $this->assoc['mac'] = $this->shared_secret('sha1'); + $this->assoc['handle'] = $this->assoc_handle(); + } + + /** + * Encrypts the MAC key using DH key exchange. + */ + protected function dh() + { + if(empty($this->data['openid_dh_modulus'])) { + $this->data['openid_dh_modulus'] = $this->default_modulus; + } + + if(empty($this->data['openid_dh_gen'])) { + $this->data['openid_dh_gen'] = $this->default_gen; + } + + if(empty($this->data['openid_dh_consumer_public'])) { + $this->directErrorResponse(); + } + + $modulus = $this->b64dec($this->data['openid_dh_modulus']); + $gen = $this->b64dec($this->data['openid_dh_gen']); + $consumerKey = $this->b64dec($this->data['openid_dh_consumer_public']); + + $privateKey = $this->keygen(strlen($modulus)); + $publicKey = $this->powmod($gen, $privateKey, $modulus); + $ss = $this->powmod($consumerKey, $privateKey, $modulus); + + $mac = $this->x_or(hash($this->assoc['hash'], $ss, true), $this->shared_secret($this->assoc['hash'])); + $this->assoc['dh_server_public'] = $this->decb64($publicKey); + $this->assoc['mac'] = base64_encode($mac); + } + + /** + * XORs two strings. + * @param String $a + * @param String $b + * @return String $a ^ $b + */ + protected function x_or($a, $b) + { + $length = strlen($a); + for($i = 0; $i < $length; $i++) { + $a[$i] = $a[$i] ^ $b[$i]; + } + + return $a; + } + + /** + * Prepares an indirect response url. + * @param array $params Parameters to be sent. + */ + protected function response($params) + { + $params += array('openid.ns' => $this->ns); + return $this->data['openid_return_to'] + . (strpos($this->data['openid_return_to'],'?') ? '&' : '?') + . http_build_query($params, '', '&'); + } + + /** + * Outputs a direct error. + */ + protected function errorResponse() + { + if(!empty($this->data['openid_return_to'])) { + $response = array( + 'openid.mode' => 'error', + 'openid.error' => 'Invalid request' + ); + $this->redirect($this->response($response)); + } else { + header('HTTP/1.1 400 Bad Request'); + $response = array( + 'ns' => $this->ns, + 'error' => 'Invalid request' + ); + echo $this->keyValueForm($response); + } + die(); + } + + /** + * Sends an positive assertion. + * @param String $identity the OP-Local Identifier that is being authenticated. + * @param Array $attributes User attributes to be sent. + */ + protected function positiveResponse($identity, $attributes) + { + # We generate a private association if there is none established. + if(!$this->assoc) { + $this->generateAssociation(); + $this->assoc['private'] = true; + } + + # We set openid.identity (and openid.claimed_id if necessary) to our $identity + if($this->data['openid_identity'] == $this->data['openid_claimed_id'] || $this->select_id) { + $this->data['openid_claimed_id'] = $identity; + } + $this->data['openid_identity'] = $identity; + + # Preparing fields to be signed + $params = array( + 'op_endpoint' => $this->serverLocation, + 'claimed_id' => $this->data['openid_claimed_id'], + 'identity' => $this->data['openid_identity'], + 'return_to' => $this->data['openid_return_to'], + 'realm' => $this->data['openid_realm'], + 'response_nonce' => gmdate("Y-m-d\TH:i:s\Z"), + 'assoc_handle' => $this->assoc['handle'], + ); + + $params += $this->responseAttributes($attributes); + + # Has the RP used an invalid association handle? + if (isset($this->data['openid_assoc_handle']) + && $this->data['openid_assoc_handle'] != $this->assoc['handle'] + ) { + $params['invalidate_handle'] = $this->data['openid_assoc_handle']; + } + + # Signing the $params + $sig = hash_hmac($this->assoc['hash'], $this->keyValueForm($params), $this->assoc['mac'], true); + $req = array( + 'openid.mode' => 'id_res', + 'openid.signed' => implode(',', array_keys($params)), + 'openid.sig' => base64_encode($sig), + ); + + # Saving the nonce and commiting the association. + $this->assoc['nonce'] = $params['response_nonce']; + $this->setAssoc($this->assoc['handle'], $this->assoc); + + # Preparing and sending the response itself + foreach($params as $name => $value) { + $req['openid.' . $name] = $value; + } + + $this->redirect($this->response($req)); + } + + /** + * Prepares an array of attributes to send + */ + protected function responseAttributes($attributes) + { + if(!$attributes) return array(); + + $ns = 'http://axschema.org/'; + + $response = array(); + if(isset($this->data['ax'])) { + $response['ns.ax'] = 'http://openid.net/srv/ax/1.0'; + foreach($attributes as $name => $value) { + $alias = strtr($name, '/', '_'); + $response['ax.type.' . $alias] = $ns . $name; + $response['ax.value.' . $alias] = $value; + } + return $response; + } + + foreach($attributes as $name => $value) { + if(!isset($this->ax_to_sreg[$name])) { + continue; + } + + $response['sreg.' . $this->ax_to_sreg[$name]] = $value; + } + return $response; + } + + /** + * Encodes fields in key-value form. + * @param Array $params Fields to be encoded. + * @return String $params in key-value form. + */ + protected function keyValueForm($params) + { + $str = ''; + foreach($params as $name => $value) { + $str .= "$name:$value\n"; + } + + return $str; + } + + /** + * Responds with an information that the user has canceled authentication. + */ + protected function cancel() + { + $this->redirect($this->response(array('openid.mode' => 'cancel'))); + } + + /** + * Converts base64 encoded number to it's decimal representation. + * @param String $str base64 encoded number. + * @return String Decimal representation of that number. + */ + protected function b64dec($str) + { + $bytes = unpack('C*', base64_decode($str)); + $n = 0; + foreach($bytes as $byte) { + $n = $this->add($this->mul($n, 256), $byte); + } + + return $n; + } + + /** + * Complements b64dec. + */ + protected function decb64($num) + { + $bytes = array(); + while($num) { + array_unshift($bytes, $this->mod($num, 256)); + $num = $this->div($num, 256); + } + + if($bytes && $bytes[0] > 127) { + array_unshift($bytes,0); + } + + array_unshift($bytes, 'C*'); + + return base64_encode(call_user_func_array('pack', $bytes)); + } + + function __call($name, $args) + { + switch($name) { + case 'add': + case 'mul': + case 'pow': + case 'mod': + case 'div': + case 'powmod': + if(function_exists('gmp_strval')) { + return gmp_strval(call_user_func_array($this->$name, $args)); + } + return call_user_func_array($this->$name, $args); + default: + throw new BadMethodCallException(); + } + } +} diff --git a/Model/UserManager.php b/Model/UserManager.php index 8513b12..4dfca60 100644 --- a/Model/UserManager.php +++ b/Model/UserManager.php @@ -11,7 +11,7 @@ class UserManager implements UserManagerInterface { /** - * @var \Fp\OpenIdBundle\Model\IdentityManagerInterface + * @var IdentityManagerInterface */ protected $identityManager; @@ -34,11 +34,11 @@ public function loadUserByUsername($username) /** * @param string $identity * - * @throws \Symfony\Component\Security\Core\Exception\UsernameNotFoundException if identity not found. - * @throws \Symfony\Component\Security\Core\Exception\UsernameNotFoundException if identity does not implement UserIdentityInterface. - * @throws \Symfony\Component\Security\Core\Exception\UsernameNotFoundException if user identity does not a user instance set. - * * @return UserInterface + * @throws UsernameNotFoundException if identity does not implement UserIdentityInterface. + * @throws UsernameNotFoundException if user identity does not a user instance set. + * + * @throws UsernameNotFoundException if identity not found. */ protected function loadUserByIdentity($identity) { diff --git a/RelyingParty/AbstractRelyingParty.php b/RelyingParty/AbstractRelyingParty.php index 94272b1..7c5655f 100644 --- a/RelyingParty/AbstractRelyingParty.php +++ b/RelyingParty/AbstractRelyingParty.php @@ -1,6 +1,9 @@ get('optional_attributes', array()); } -} \ No newline at end of file +} diff --git a/RelyingParty/IdentityProviderResponse.php b/RelyingParty/IdentityProviderResponse.php index b4b0f30..07afc08 100644 --- a/RelyingParty/IdentityProviderResponse.php +++ b/RelyingParty/IdentityProviderResponse.php @@ -1,4 +1,5 @@ identity, $this->attributes) = unserialize($serialized); } -} \ No newline at end of file +} diff --git a/RelyingParty/RecoveredFailureRelyingParty.php b/RelyingParty/RecoveredFailureRelyingParty.php index 85974fb..4599145 100644 --- a/RelyingParty/RecoveredFailureRelyingParty.php +++ b/RelyingParty/RecoveredFailureRelyingParty.php @@ -1,4 +1,5 @@ getToken()->getAttributes() ); } -} \ No newline at end of file +} diff --git a/RelyingParty/RelyingPartyCollection.php b/RelyingParty/RelyingPartyCollection.php index c3c6d86..0466bac 100644 --- a/RelyingParty/RelyingPartyCollection.php +++ b/RelyingParty/RelyingPartyCollection.php @@ -47,9 +47,9 @@ public function manage(Request $request) } /** - * @param \Symfony\Component\HttpFoundation\Request $request + * @param Request $request * - * @return \Fp\OpenIdBundle\RelyingPartyRelyingPartyInterface|null + * @return RelyingPartyInterface|null */ protected function findRelyingPartySupportedRequest(Request $request) { @@ -59,4 +59,4 @@ protected function findRelyingPartySupportedRequest(Request $request) } } } -} \ No newline at end of file +} diff --git a/Resources/config/mongodb.xml b/Resources/config/mongodb.xml index f50b3a3..b9aeec6 100644 --- a/Resources/config/mongodb.xml +++ b/Resources/config/mongodb.xml @@ -20,4 +20,4 @@ - \ No newline at end of file + diff --git a/Resources/config/orm.xml b/Resources/config/orm.xml index cd7309d..44a496b 100644 --- a/Resources/config/orm.xml +++ b/Resources/config/orm.xml @@ -20,4 +20,4 @@ - \ No newline at end of file + diff --git a/Resources/config/services.xml b/Resources/config/services.xml index 2ede311..c17be31 100644 --- a/Resources/config/services.xml +++ b/Resources/config/services.xml @@ -1,61 +1,62 @@ - + Fp\OpenIdBundle\Security\Core\Authentication\Provider\OpenIdAuthenticationProvider Fp\OpenIdBundle\Security\Http\Firewall\OpenIdAuthenticationListener Fp\OpenIdBundle\Security\Core\Authorization\Voter\OpenIdAuthenticatedVoter - Fp\OpenIdBundle\Bridge\RelyingParty\LightOpenIdRelyingParty Fp\OpenIdBundle\RelyingParty\RecoveredFailureRelyingParty Fp\OpenIdBundle\RelyingParty\RelyingPartyCollection - - + - - + id="security.authentication.listener.fp_openid" + class="%security.authentication.listener.fp_openid.class%" + parent="security.authentication.listener.abstract" + public="false" + abstract="true" + /> - + - + - + - + - + + + + + - \ No newline at end of file + diff --git a/Resources/views/Security/login.html.twig b/Resources/views/Security/login.html.twig index 14be66b..c353747 100644 --- a/Resources/views/Security/login.html.twig +++ b/Resources/views/Security/login.html.twig @@ -12,4 +12,4 @@ -{% endblock fp_openid_content %} \ No newline at end of file +{% endblock fp_openid_content %} diff --git a/Security/Core/Authentication/Provider/OpenIdAuthenticationProvider.php b/Security/Core/Authentication/Provider/OpenIdAuthenticationProvider.php index 44fe310..c67433d 100644 --- a/Security/Core/Authentication/Provider/OpenIdAuthenticationProvider.php +++ b/Security/Core/Authentication/Provider/OpenIdAuthenticationProvider.php @@ -21,12 +21,12 @@ class OpenIdAuthenticationProvider implements AuthenticationProviderInterface protected $providerKey; /** - * @var null|\Symfony\Component\Security\Core\User\UserProviderInterface + * @var null|UserProviderInterface */ protected $userProvider; /** - * @var null|\Symfony\Component\Security\Core\User\UserCheckerInterface + * @var null|UserCheckerInterface */ protected $userChecker; @@ -36,8 +36,9 @@ class OpenIdAuthenticationProvider implements AuthenticationProviderInterface protected $createIfNotExists; /** - * @param null|\Symfony\Component\Security\Core\User\UserProviderInterface $userProvider - * @param null|\Symfony\Component\Security\Core\User\UserCheckerInterface $userChecker + * @param string $providerKey + * @param null|UserProviderInterface $userProvider + * @param null|UserCheckerInterface $userChecker * @param bool $createIfNotExists */ public function __construct($providerKey, UserProviderInterface $userProvider = null, UserCheckerInterface $userChecker = null, $createIfNotExists = false) @@ -106,7 +107,7 @@ public function supports(TokenInterface $token) * * @throws \RuntimeException if provider did not provide a user implementation. * - * @return \Symfony\Component\Security\Core\User\UserInterface + * @return UserInterface */ protected function getProviderUser($identity, array $attributes) { @@ -128,7 +129,7 @@ protected function getProviderUser($identity, array $attributes) } /** - * @param \Fp\OpenIdBundle\Security\Core\Authentication\Token\OpenIdToken $token + * @param OpenIdToken $token * * @return string */ @@ -143,7 +144,7 @@ protected function getDefaultUser($identity, array $attributes) * @param array $roles * @param mixed $user * - * @return \Fp\OpenIdBundle\Security\Core\Authentication\Token\OpenIdToken + * @return OpenIdToken */ protected function createAuthenticatedToken($identity, array $attributes, array $roles, $user) { @@ -158,4 +159,4 @@ protected function createAuthenticatedToken($identity, array $attributes, array return $newToken; } -} \ No newline at end of file +} diff --git a/Security/Core/Authentication/Token/OpenIdToken.php b/Security/Core/Authentication/Token/OpenIdToken.php index eb6d21c..9a2bad4 100644 --- a/Security/Core/Authentication/Token/OpenIdToken.php +++ b/Security/Core/Authentication/Token/OpenIdToken.php @@ -44,7 +44,7 @@ public function getIdentity() } /** - * @return void + * @return string */ public function getCredentials() { @@ -54,18 +54,28 @@ public function getCredentials() /** * {@inheritdoc} */ - public function serialize() + public function __serialize(): array { - return serialize(array($this->providerKey, $this->identity, parent::serialize())); + return array( + $this->providerKey, + $this->identity, + \is_callable('parent::__serialize') ? parent::__serialize() : unserialize(parent::serialize()), + ); } /** * {@inheritdoc} */ - public function unserialize($str) + public function __unserialize(array $data): void { - list($this->providerKey, $this->identity, $parentStr) = unserialize($str); + list($this->providerKey, $this->identity, $parentData) = $data; + + $parentData = \is_array($parentData) ? $parentData : unserialize($parentData); - parent::unserialize($parentStr); + if (\is_callable('parent::__serialize')) { + parent::__unserialize($parentData); + } else { + parent::unserialize(serialize($parentData)); + } } } diff --git a/Security/Core/Authorization/Voter/OpenIdAuthenticatedVoter.php b/Security/Core/Authorization/Voter/OpenIdAuthenticatedVoter.php index a284c15..2f0894c 100644 --- a/Security/Core/Authorization/Voter/OpenIdAuthenticatedVoter.php +++ b/Security/Core/Authorization/Voter/OpenIdAuthenticatedVoter.php @@ -44,4 +44,4 @@ public function vote(TokenInterface $token, $object, array $attributes) return VoterInterface::ACCESS_ABSTAIN; } -} \ No newline at end of file +} diff --git a/Security/Core/User/UserManagerInterface.php b/Security/Core/User/UserManagerInterface.php index ccda327..395b749 100644 --- a/Security/Core/User/UserManagerInterface.php +++ b/Security/Core/User/UserManagerInterface.php @@ -1,6 +1,8 @@ getRelyingParty()->supports($request); } -} \ No newline at end of file +} diff --git a/Security/Http/Firewall/OpenIdAuthenticationListener.php b/Security/Http/Firewall/OpenIdAuthenticationListener.php index 6c2d018..bcfdc1c 100644 --- a/Security/Http/Firewall/OpenIdAuthenticationListener.php +++ b/Security/Http/Firewall/OpenIdAuthenticationListener.php @@ -25,8 +25,8 @@ protected function attemptAuthentication(Request $request) $result = $this->getRelyingParty()->manage($openIdRequest); - if ($result instanceof RedirectResponse) { - if ($targetUrl = $request->get($this->options['target_path_parameter'], null, true)) { + if ($result instanceof RedirectResponse) { + if ($targetUrl = $request->get($this->options['target_path_parameter'])) { $request->getSession()->set('_security.' . $this->providerKey . '.target_path', $targetUrl); } diff --git a/Tests/Functional/app/WebTestCase.php b/Tests/Functional/app/WebTestCase.php index 7face3c..4093e97 100644 --- a/Tests/Functional/app/WebTestCase.php +++ b/Tests/Functional/app/WebTestCase.php @@ -18,4 +18,4 @@ public static function getKernelClass() return 'AppKernel'; } -} \ No newline at end of file +} diff --git a/Tests/Security/Core/Authentication/Token/OpenIdTokenTest.php b/Tests/Security/Core/Authentication/Token/OpenIdTokenTest.php index e3e2b43..5514d72 100644 --- a/Tests/Security/Core/Authentication/Token/OpenIdTokenTest.php +++ b/Tests/Security/Core/Authentication/Token/OpenIdTokenTest.php @@ -59,7 +59,7 @@ public function shouldUnserializeIdentity() $expectedIdentity = 'the_identity'; $token = new OpenIdToken('provider_key', $expectedIdentity); - + $unserializedToken = unserialize(serialize($token)); $this->assertEquals($expectedIdentity, $unserializedToken->getIdentity()); diff --git a/composer.json b/composer.json index a89acd0..db9b2e1 100644 --- a/composer.json +++ b/composer.json @@ -17,8 +17,7 @@ ], "require": { "php": ">=5.3.2", - "lightopenid/lightopenid": "dev-master", - "symfony/symfony": "~2.7|3.*" + "symfony/framework-bundle": "^2.8 || ^3.0 || ^4.0" }, "require-dev": { "phpunit/phpunit": "~3.7" @@ -33,10 +32,5 @@ "target-dir": "Fp/OpenIdBundle", "config": { "bin-dir": "bin" - }, - "extra": { - "branch-alias": { - "dev-master": "2.7-dev" - } } }