2017-02-02 1 views
1

oauth2를 사용하여 PFX 파일과 암호를 사용하여 회사 API에 연결해야합니다.PHP를 사용하여 PFX 파일과 비밀번호로 API에 연결하는 방법은 무엇입니까?

PFX 파일 사용에 익숙하지 않고 PFX 파일과 암호를 사용하여 API에 연결하는 방법을 잘 모릅니다. 나는 여기에서 보았으나 시작하는데 도움이되는 것을 많이 찾지 못했습니다. Google을 검색했지만 몇 가지 문서와 샘플 코드를 찾았습니다. 아무 것도 작동하지 않았습니다. 다음 코드를 찾았지만 작동하지 않습니다. 누군가 내가이 일을하도록 도와 줄 수 있습니까?

<?php 

$url = "https://myaccounts.domain.com/auth/oauth/v2/token"; 
$cert_file = 'my_auth.pfx'; 
$cert_password = '1234567890'; 

$ch = curl_init(); 

$options = array( 
    CURLOPT_RETURNTRANSFER => true, 

    //CURLOPT_HEADER   => true, 
    CURLOPT_FOLLOWLOCATION => true, 
    CURLOPT_SSL_VERIFYHOST => false, 
    CURLOPT_SSL_VERIFYPEER => false, 

    CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)', 

    //CURLOPT_VERBOSE  => true, 
    CURLOPT_URL => $url , 
    CURLOPT_SSLCERT => $cert_file , 
    CURLOPT_SSLCERTPASSWD => $cert_password , 
); 

curl_setopt_array($ch , $options); 

$output = curl_exec($ch); 

if(!$output) 
{ 
    echo "Curl Error : " . curl_error($ch); 
} 
else 
{ 
    echo htmlentities($output); 
} 
?> 

위의 코드는 나에게 다음과 같은 오류 제공 :

Curl Error: could not load PEM client certificate, OpenSSL error error:02001002:system library:fopen:No such file or directory, (no key found, wrong pass phrase, or wrong file format?) 

의 핵심은 같은 디렉토리에를 다음과 같이

코드 나는 발견하고 현재 사용하는 시도하고있다했습니다 그래서 왜 그것을 발견하지 못했습니다. 아마도 PFX 파일을 잘못 사용하고 있습니다.

답변

0

이 모든 것이 잘못되었습니다. 필자가 읽은 내용과 수집 한 정보를 바탕으로 PFX 파일을 PEM 파일로 변환하는 것이 가장 좋습니다. 나는 cygwin을 사용하여 필요한 모든 패키지와 openssl을 사용했다. 일단 PFX 파일이 PEM으로 변환되면 데이터를 가져와야하는 API에 연결하는 데 필요한 자격 증명이있는 말풍선 명령을 사용했습니다. 내가 bash 쉘에서 실행 명령은 다음

* timeout on name lookup is not supported 
* Trying 123.123.123.123... 
* TCP_NODELAY set 
    % Total % Received % Xferd Average Speed Time Time  Time Current 
           Dload Upload Total Spent Left Speed 
    0  0 0  0 0  0  0  0 --:--:-- --:--:-- --:--:--  0* Connected to myaccounts.domain.com (123.123.123.123) port 111 (#0) 
* ALPN, offering h2 
* ALPN, offering http/1.1 
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH 
* successfully set certificate verify locations: 
* CAfile: C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt 
    CApath: none 
* TLSv1.2 (OUT), TLS header, Certificate Status (22): 
} [5 bytes data] 
* TLSv1.2 (OUT), TLS handshake, Client hello (1): 
} [512 bytes data] 
* TLSv1.2 (IN), TLS handshake, Server hello (2): 
{ [87 bytes data] 
* TLSv1.2 (IN), TLS handshake, Certificate (11): 
{ [3880 bytes data] 
* TLSv1.2 (IN), TLS handshake, Server key exchange (12): 
{ [333 bytes data] 
* TLSv1.2 (IN), TLS handshake, Request CERT (13): 
{ [903 bytes data] 
* TLSv1.2 (IN), TLS handshake, Server finished (14): 
{ [4 bytes data] 
* TLSv1.2 (OUT), TLS handshake, Certificate (11): 
} [1291 bytes data] 
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16): 
} [70 bytes data] 
* TLSv1.2 (OUT), TLS handshake, CERT verify (15): 
} [264 bytes data] 
* TLSv1.2 (OUT), TLS change cipher, Client hello (1): 
} [1 bytes data] 
* TLSv1.2 (OUT), TLS handshake, Finished (20): 
} [16 bytes data] 
* TLSv1.2 (IN), TLS change cipher, Client hello (1): 
{ [1 bytes data] 
* TLSv1.2 (IN), TLS handshake, Finished (20): 
{ [16 bytes data] 
* SSL connection using TLSv1.2/ECDHE-RSA-AES256-SHA 
* ALPN, server did not agree to a protocol 
* Server certificate: 
* subject: C=US; ST=My Location; L=ThankYou; O=Automatic Data Processing, Inc.; OU=Testing Labs; CN=myaccounts.domain.com 
* start date: Aug 4 00:00:00 2001 GMT 
* expire date: Oct 23 01:01:01 2017 GMT 
* issuer: C=US; O=My Corporation; OU=My Trust Network; CN=My Class 3 Secure Server CA - G4 
* SSL certificate verify ok. 
* Server auth using Basic with user '123456' 
} [5 bytes data] 
> POST /auth/oauth/v2/token HTTP/1.1 
> Host: myaccounts.domain.com 
> Authorization: Basic veryveryveryveryverylongstringthatwillgoherebecauseitisveryverylong== 
> User-Agent: curl/6.12.0 
> Accept: */* 
> 
    0  0 0  0 0  0  0  0 --:--:-- 0:00:01 --:--:--  0{ [5 bytes data] 
< HTTP/1.1 200 OK 
< MY-CorrelationID: 123456789-adda-1234-a123-1a12345abcde 
< Pragma: no-cache 
< Cache-Control: no-store, no-cache, private 
< Content-Type: application/json;charset=UTF-8 
< Content-Length: 127 
< Date: Thu, 02 Feb 2017 23:05:46 GMT 
< Server: My Accounts 
< 
{ [127 bytes data] 
100 127 100 127 0  0  75  0 0:00:01 0:00:01 --:--:-- 77* Curl_http_done: called premature == 0 
100 127 100 127 0  0  75  0 0:00:01 0:00:01 --:--:-- 77HTTP/1.1 200 OK 
MY-CorrelationID: 123456789-adda-1234-a123-1a12345abcde 
Pragma: no-cache 
Cache-Control: no-store, no-cache, private 
Content-Type: application/json;charset=UTF-8 
Content-Length: 127 
Date: Thu, 02 Feb 2017 23:05:46 GMT 
Server: My Accounts 

{ 
    "access_token":"123456789-1234-1234-1234-123456789", 
    "token_type":"Bearer", 
    "expires_in":3600, 
    "scope":"api" 
} 
* Connection #0 to host myaccounts.domain.com left intact 

가 나는 또한 우체부를 사용하여이 연결을 확인 할 수 있었다, 나는 일관되게 같은 응답을 얻을 :

curl -i -XPOST -u username:password -k https://myaccounts.domain.com/auth/oauth/v2/token -v --cert my_auth.pem 

나는 다음과 같은 응답을 받았습니다 .

필자가 수행 한 연구를 바탕으로 내 필요에 맞는 솔루션을 개발합니다. cURL을 사용하는 PHP 솔루션은 다음과 같습니다. 아래는 두 가지 기능과 if 조건입니다. if 조건은 액세스 토큰이 세션에 이미 추가되었는지 여부에 따라 적절한 함수를 시작합니다. 세션에 추가되지 않으면 추가해야하는 자격 증명에 따라 세션을 가져옵니다. 세션에 이미 추가 된 경우 필요한 데이터를 가져옵니다. http://php.net/manual/en/book.curl.php

<?php 

session_start(); 

function getAccessCode(){ 

    $curl = curl_init(); 

    // Variables 
    $apiGrantType = 'client_credentials'; 
    $apiScopes = array('scope1','scope2','scope3');    // Currently not used 
    $apiUrl = "myaccounts.domain.com/auth/oauth/v2/token?grant_type=" . $apiGrantType; 
    $authPath = '/var/www/html/domain.com/clients/test/'; 
    $cliendId = 'username';          // Client ID 
    $clientSecret = 'password';         // Client Secret 
    $certUserPwd = $cliendId . ":" . $clientSecret;    // Client ID:Client Secret 
    $certFile = $authPath . 'my_auth.pem';      // Private Cert 
    $certPassword = 'cert-password';       // Cert Password 

    $apiPost = array(
     "grant_type" => $apiGrantType, 
     "client_id"  => $cliendId, 
     "client_secret" => $clientSecret 
    ); 
    $apiPostQuery = http_build_query($apiPost); 

    $apiHeader = array(); 

    // $header Content Length 
    $apiHeader[] = 'Content-length: 0'; 

    // $header Content Type 
    $apiHeader[] = 'Content-type: application/json'; 

    // $header 'Client ID:Client Secret' Base64 Encoded 
    $apiHeader[] = "Authorization: Basic " . base64_encode($cliendId . ":" . $clientSecret); // OAuth,Basic 

    // cURL Options 
    $options = array(

     CURLOPT_URL     => $apiUrl, 

     CURLOPT_RETURNTRANSFER  => true, 

     CURLOPT_HEADER    => false, // true to show header information 
     CURLINFO_HEADER_OUT   => true, 
     CURLOPT_HTTPGET    => false, 
     CURLOPT_POST    => true, 
     CURLOPT_FOLLOWLOCATION  => false, 
     CURLOPT_VERBOSE    => true, 
     CURLOPT_FOLLOWLOCATION  => true, 

     CURLOPT_SSL_VERIFYHOST  => false, // true in production 
     CURLOPT_SSL_VERIFYPEER  => false, // true in production 

     CURLOPT_TIMEOUT    => 30, 
     CURLOPT_MAXREDIRS   => 2, 

     CURLOPT_HTTPHEADER   => $apiHeader, 
     CURLOPT_USERAGENT   => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)', 

     CURLOPT_HTTPAUTH   => CURLAUTH_ANYSAFE, // CURLAUTH_BASIC 
     CURLOPT_POSTFIELDS   => $apiPostQuery, 

     CURLOPT_USERPWD    => $certUserPwd, 
     CURLOPT_SSLCERTTYPE   => 'PEM', 
     CURLOPT_SSLCERT    => $certFile, 
     CURLOPT_SSLCERTPASSWD  => $certPassword 
    ); 

    curl_setopt_array($curl , $options); 
    $output = curl_exec($curl); 
    $json = json_decode($output); 

    return $json->access_token; 
} 


function getJobApps($access_token) { 

    echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; 

    /** 
    * Get Job Applications Data from DOMAIN 
    */ 
    $curl = curl_init(); 

    $apiUrl = "https://myaccounts.domain.com/aaaaa/bbbbb"; 

    // $header Authorization 
    $apiHeader = array('Authorization', 'Bearer ' . $access_token); 

    $options = array(
     CURLOPT_URL    => $apiUrl, 
     CURLOPT_HTTPHEADER  => $apiHeader, 
     CURLOPT_RETURNTRANSFER => true, 
     CURLOPT_POST   => true 
    ); 

    curl_setopt_array($curl , $options); 
    $output = curl_exec($curl); 
    $json = json_decode($output); 

    echo '<pre>'; 
    print_r($json); 
    echo '</pre>'; 
} 


// Init Loop 
if(isset($_SESSION['access_token'])) { 

    // Job Applications 
    $apiData = getJobApps($_SESSION['access_token']); 

    echo $apiData; 

} else { 
    $access_token = getAccessCode(); 
    $_SESSION['access_token'] = $access_token; 

    echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; 

    header(sprintf("Location: %s", 'http://mywebsite.com/clients/test/test.php')); 
    die(); 
} 

?> 
:

나는 나의 OP에 확장을위한 PHP 컬 문서를 사용

관련 문제