2011-07-17 4 views
1

class.openid.php
lightopenid
보다 간단하고 작기 때문에 공부하려고합니다. 내 목적에 따라 200 줄이 중요합니다.class.openid.php가 google openID로 작업 한 사람이 있습니까?

ERROR CODE: OPENID_NOSERVERSFOUND 
ERROR DESCRIPTION: Cannot find OpenID Server TAG on Identity page. 

이 class.openid.php (모든 버전)을 만드는 것이 가능하다 그런 일을 구글 오픈 아이디 어떻게 작동 : 그러나 class.openid.php 나에게, 구글 오픈 아이디 https://www.google.com/accounts/o8/id과 같은 오류를 인쇄 작동하지 않는 이유는 무엇입니까?

HTML : 그래서 내가있어 코드를보고 싶은 모든 <?을 찾을 경우 누군가에 <?php에 탐을 대체했다

class.openid.phphere 취할 수 있지만, 상자 밖으로 나를 위해 일하지 않았다 인터페이스 페이지 :

<?php 
require('class.openid.v3.php'); 

if ($_POST['openid_action'] == "login"){ // Get identity from user and redirect browser to OpenID Server 
    $openid = new SimpleOpenID; 
    $openid->SetIdentity($_POST['openid_url']); 
    $openid->SetTrustRoot('http://' . $_SERVER["HTTP_HOST"]); 
    $openid->SetRequiredFields(array('email','fullname')); 
    $openid->SetOptionalFields(array('dob','gender','postcode','country','language','timezone')); 
    if ($openid->GetOpenIDServer()){ 
     $openid->SetApprovedURL('http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PATH_INFO"]);  // Send Response from OpenID server to this script 
     $openid->Redirect(); // This will redirect user to OpenID Server 
    }else{ 
     $error = $openid->GetError(); 
     echo "ERROR CODE: " . $error['code'] . "<br>"; 
     echo "ERROR DESCRIPTION: " . $error['description'] . "<br>"; 
    } 
    exit; 
} 
else if($_GET['openid_mode'] == 'id_res'){ // Perform HTTP Request to OpenID server to validate key 
    $openid = new SimpleOpenID; 
    $openid->SetIdentity($_GET['openid_identity']); 
    $openid_validation_result = $openid->ValidateWithServer(); 
    if ($openid_validation_result == true){   // OK HERE KEY IS VALID 
     echo "VALID"; 
    }else if($openid->IsError() == true){   // ON THE WAY, WE GOT SOME ERROR 
     $error = $openid->GetError(); 
     echo "ERROR CODE: " . $error['code'] . "<br>"; 
     echo "ERROR DESCRIPTION: " . $error['description'] . "<br>"; 
    }else{           // Signature Verification Failed 
     echo "INVALID AUTHORIZATION"; 
    } 
}else if ($_GET['openid_mode'] == 'cancel'){ // User Canceled your Request 
    echo "USER CANCELED REQUEST"; 
} 
?> 
<html> 
<head> 
    <title>OpenID Example</title> 
</head> 
<body> 
<div> 
<fieldset id="openid"> 
<legend>OpenID Login</legend> 
<form action="<?php echo 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PATH_INFO"]; ?>" method="post" onsubmit="this.login.disabled=true;"> 
<input type="hidden" name="openid_action" value="login"> 
<div><input type="text" name="openid_url" class="openid_login"><input type="submit" name="login" value="login &gt;&gt;"></div> 
<div><a href="http://www.myopenid.com/" class="link" >Get an OpenID</a></div> 
</form> 
</fieldset> 
</div> 
<div style="margin-top: 2em; font-family: arial; font-size: 0.8em; border-top:1px solid gray; padding: 4px;">Sponsored by: <a href="http://www.fivestores.com">FiveStores</a> - get your free online store; includes extensive API for developers; <i style="color: gray;">integrated with <a href="http://en.wikipedia.org/wiki/OpenID">OpenID</a></i></div> 
</body> 
</html> 

와 PHP 클래스

<?php 
/* 
    FREE TO USE Under License: GPLv3 
    Simple OpenID PHP Class 
    Some modifications by Eddie Roosenmaallen, [email protected] 
*/ 

class SimpleOpenID{ 
    var $openid_url_identity; 
    var $URLs = array(); 
    var $error = array(); 
    var $fields = array(
     'required' => array(), 
     'optional' => array(), 
    ); 

    function SimpleOpenID(){ 
     if (!function_exists('curl_exec')) { 
      die('Error: Class SimpleOpenID requires curl extension to work'); 
     } 
    } 

    function SetOpenIDServer($a){ 
     $this->URLs['openid_server'] = $a; 
    } 

    function SetTrustRoot($a){ 
     $this->URLs['trust_root'] = $a; 
    } 

    function SetCancelURL($a){ 
     $this->URLs['cancel'] = $a; 
    } 

    function SetApprovedURL($a){ 
     $this->URLs['approved'] = $a; 
    } 

    function SetRequiredFields($a){ 
     if (is_array($a)){ 
      $this->fields['required'] = $a; 
     }else{ 
      $this->fields['required'][] = $a; 
     } 
    } 

    function SetOptionalFields($a){ 
     if (is_array($a)){ 
      $this->fields['optional'] = $a; 
     }else{ 
      $this->fields['optional'][] = $a; 
     } 
    } 

    function SetIdentity($a){ // Set Identity URL 
      if ((stripos($a, 'http://') === false) 
       && (stripos($a, 'https://') === false)){ 
       $a = 'http://'.$a; 
      } 
      $this->openid_url_identity = $a; 
    } 

    function GetIdentity(){  // Get Identity 
     return $this->openid_url_identity; 
    } 

    function GetError(){ 
     $e = $this->error; 
     return array('code'=>$e[0],'description'=>$e[1]); 
    } 

    function ErrorStore($code, $desc = null){ 
     $errs['OPENID_NOSERVERSFOUND'] = 'Cannot find OpenID Server TAG on Identity page.'; 
     if ($desc == null){ 
      $desc = $errs[$code]; 
     } 
     $this->error = array($code,$desc); 
    } 

    function IsError(){ 
     if (count($this->error) > 0){ 
      return true; 
     }else{ 
      return false; 
     } 
    } 

    function splitResponse($response) { 
     $r = array(); 
     $response = explode("\n", $response); 
     foreach($response as $line) { 
      $line = trim($line); 
      if ($line != "") { 
       list($key, $value) = explode(":", $line, 2); 
       $r[trim($key)] = trim($value); 
      } 
     } 
     return $r; 
    } 

    function OpenID_Standarize($openid_identity = null){ 
     if ($openid_identity === null) 
      $openid_identity = $this->openid_url_identity; 

     $u = parse_url(strtolower(trim($openid_identity))); 

     if (!isset($u['path']) || ($u['path'] == '/')) { 
      $u['path'] = ''; 
     } 
     if(substr($u['path'],-1,1) == '/'){ 
      $u['path'] = substr($u['path'], 0, strlen($u['path'])-1); 
     } 
     if (isset($u['query'])){ // If there is a query string, then use identity as is 
      return $u['host'] . $u['path'] . '?' . $u['query']; 
     }else{ 
      return $u['host'] . $u['path']; 
     } 
    } 

    function array2url($arr){ // converts associated array to URL Query String 
     if (!is_array($arr)){ 
      return false; 
     } 
     $query = ''; 
     foreach($arr as $key => $value){ 
      $query .= $key . "=" . $value . "&"; 
     } 
     return $query; 
    } 

    function CURL_Request($url, $method="GET", $params = "") { // Remember, SSL MUST BE SUPPORTED 
      if (is_array($params)) $params = $this->array2url($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_SSL_VERIFYPEER, false); 
      curl_setopt($curl, CURLOPT_HTTPGET, ($method == "GET")); 
      curl_setopt($curl, CURLOPT_POST, ($method == "POST")); 
      if ($method == "POST") curl_setopt($curl, CURLOPT_POSTFIELDS, $params); 
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
      $response = curl_exec($curl); 

      if (curl_errno($curl) == 0){ 
       $response; 
      }else{ 
       $this->ErrorStore('OPENID_CURL', curl_error($curl)); 
      } 
      return $response; 
    } 

    function HTML2OpenIDServer($content) { 
     $get = array(); 

     // Get details of their OpenID server and (optional) delegate 
     preg_match_all('/<link[^>]*rel=[\'"]openid.server[\'"][^>]*href=[\'"]([^\'"]+)[\'"][^>]*\/?>/i', $content, $matches1); 
     preg_match_all('/<link[^>]*href=\'"([^\'"]+)[\'"][^>]*rel=[\'"]openid.server[\'"][^>]*\/?>/i', $content, $matches2); 
     $servers = array_merge($matches1[1], $matches2[1]); 

     preg_match_all('/<link[^>]*rel=[\'"]openid.delegate[\'"][^>]*href=[\'"]([^\'"]+)[\'"][^>]*\/?>/i', $content, $matches1); 

     preg_match_all('/<link[^>]*href=[\'"]([^\'"]+)[\'"][^>]*rel=[\'"]openid.delegate[\'"][^>]*\/?>/i', $content, $matches2); 

     $delegates = array_merge($matches1[1], $matches2[1]); 

     $ret = array($servers, $delegates); 
     return $ret; 
    } 

    function GetOpenIDServer(){ 
     $response = $this->CURL_Request($this->openid_url_identity); 
     list($servers, $delegates) = $this->HTML2OpenIDServer($response); 
     if (count($servers) == 0){ 
      $this->ErrorStore('OPENID_NOSERVERSFOUND'); 
      return false; 
     } 
     if (isset($delegates[0]) 
      && ($delegates[0] != "")){ 
      $this->SetIdentity($delegates[0]); 
     } 
     $this->SetOpenIDServer($servers[0]); 
     return $servers[0]; 
    } 

    function GetRedirectURL(){ 
     $params = array(); 
     $params['openid.return_to'] = urlencode($this->URLs['approved']); 
     $params['openid.mode'] = 'checkid_setup'; 
     $params['openid.identity'] = urlencode($this->openid_url_identity); 
     $params['openid.trust_root'] = urlencode($this->URLs['trust_root']); 

     if (isset($this->fields['required']) 
      && (count($this->fields['required']) > 0)) { 
      $params['openid.sreg.required'] = implode(',',$this->fields['required']); 
     } 
     if (isset($this->fields['optional']) 
      && (count($this->fields['optional']) > 0)) { 
      $params['openid.sreg.optional'] = implode(',',$this->fields['optional']); 
     } 
     return $this->URLs['openid_server'] . "?". $this->array2url($params); 
    } 

    function Redirect(){ 
     $redirect_to = $this->GetRedirectURL(); 
     if (headers_sent()){ // Use JavaScript to redirect if content has been previously sent (not recommended, but safe) 
      echo '<script language="JavaScript" type="text/javascript">window.location=\''; 
      echo $redirect_to; 
      echo '\';</script>'; 
     }else{ // Default Header Redirect 
      header('Location: ' . $redirect_to); 
     } 
    } 

    function ValidateWithServer(){ 
     $params = array(
      'openid.assoc_handle' => urlencode($_GET['openid_assoc_handle']), 
      'openid.signed' => urlencode($_GET['openid_signed']), 
      'openid.sig' => urlencode($_GET['openid_sig']) 
     ); 
     // Send only required parameters to confirm validity 
     $arr_signed = explode(",",str_replace('sreg.','sreg_',$_GET['openid_signed'])); 
     for ($i=0; $i<count($arr_signed); $i++){ 
      $s = str_replace('sreg_','sreg.', $arr_signed[$i]); 
      $c = $_GET['openid_' . $arr_signed[$i]]; 
      // if ($c != ""){ 
       $params['openid.' . $s] = urlencode($c); 
      // } 
     } 
     $params['openid.mode'] = "check_authentication"; 

     $openid_server = $this->GetOpenIDServer(); 
     if ($openid_server == false){ 
      return false; 
     } 
     $response = $this->CURL_Request($openid_server,'POST',$params); 
     $data = $this->splitResponse($response); 

     if ($data['is_valid'] == "true") { 
      return true; 
     }else{ 
      return false; 
     } 
    } 
} 
?> 
+0

클래스를 확장하고 누락 된 기능을 추가 할 수 있기 때문에 질문에 일반적으로 대답 할 수 있습니다 ** 예 **. 그러나 나는 그것이 당신이 요구하는 것이 아니라고 생각합니다. 당신이 찾고있는 모든 것을 가지고있는 클래스의 새로운 버전의 다운로드 링크를 선호한다고 생각합니까? – hakre

+1

나는이 200 줄의 코드가 당신에게 중요하다고 생각하지 않는다. 그럼에도 불구하고 OpenID 2를 지원하고 싶다면0 및 속성 교환을 수행하려면 다른 라이브러리를 사용해야합니다. 그리고 줄 수는 중요하지 않다는 것을 증명하기 위해, 나는 여러분이 사용하는 클래스보다 작게 만들기 위해 lightopenid에서 코드의 절반 (주석의 절반이 눈에 띄게 부족한 주석)을 제거했습니다 : http : // pastebin .com/fE8qT3kW. 속성 검색을 지원하지는 않지만 여전히 OpenID의 두 버전을 모두 지원합니다. 요약하면, LightOpenID는 복잡하지도 않고 부풀어 오른 것도 아닙니다. – Mewp

답변

2

질문의 클래스는 모두 오픈 ID 2.0을 지원하지 않습니다. 따라서 많은 코드를 추가하지 않으면 Google과 호환되지 않습니다.

4

문제는 Google이 OpenID 엔드 포인트를 제공하는 것이 아니라는 것입니다.

OpenId 끝점에는 사용자의 식별자가 포함됩니다.

우리가 여기서 가지고있는 것을 발견 URL이라고합니다.

이것은 모든 사용자를 안내 할 수있는 정적 URL이며 서비스 자체는 사용자를 인식하고 사용자 별 고유 식별 URL을 반환합니다.

그러나 이것은 공식 오픈 ID 웹 사이트에 링크 된 대부분 포함 가장 오픈 ID 클라이언트 라이브러리, 제대로 구현되지 않습니다.

Zend Framework 라이브러리조차도이를 처리 할 수 ​​없습니다.

그러나 여러 가지 관점에서 분석 한 수업을 발견했으며 매우 만족합니다. 내가 일하는 회사에서 우리는 이미 여러 프로덕션 환경에서 성공적으로 통합했으며 어떤 문제도 경험하지 않았습니다.

또 다른 내 게시물은 Facebook을 오픈 소스 제공자로 지정하는 문제를 다루고 싶습니다. 또한 구글을 지원 내가 사용하고있는 클래스는,도 찾을 수 있습니다

Best way to implement Single-Sign-On with all major providers?

+0

BTW : google openID Discovery Url을 사용하여 올바르게 수행 할 수있는 이음새 솔기 ...) – Rella

+0

예, lightopenid는 내가 사용중인 클래스입니다. –

+0

제목에서 나에게 명확한 것처럼 보였기 때문에 나는 정말로 당신의 질문을 자세히 보지 않았다. 이제 당신이 라이트 페니드로 일하는 알레 미아 인 걸 봅니다. 나는 이것에 상당한 양의 연구를 투자했고, 단지 그것에 충실 할 것을 권고 할 수있다. –

관련 문제