Program Tip

offline_access 지원 중단 이후 액세스 토큰 유효성을 확장하는 방법

programtip 2020. 12. 4. 20:24
반응형

offline_access 지원 중단 이후 액세스 토큰 유효성을 확장하는 방법


offline_access 권한 이 Facebook의 인증 흐름 에서 더 이상 사용되지 않기 때문에 해당 권한 없이 소위 수명이 긴 액세스 토큰을 가져 오는 데 문제가 있습니다.

에서 사용되지 않음에 대한 페이스 북의 문서 는 말한다, 그 서버 측 OAuth를 생성 액세스 토큰은 오래 살았 될 것입니다,하지만 그들은되지 않습니다.

내가 뭔가를 놓치고 있습니까? 앱 설정의 일부 설정? 액세스 토큰의 만료 시간을 연장하기 위해 사용해야하는 특수 코드가 있습니까? 문서를 이해했듯이 서버 측 인증을 getAccessToken()위해 사용자가 로그인했을 때 PHP SDK를 통해 액세스 할 수있는 액세스 토큰 은 오래 지속됩니다.


편집 (2012 년 8 월 14 일) :
일주일 전에 공식 Facebook PHP SDK가 업데이트되었습니다. 함수 이름이 setExtendedAccessToken 으로 변경되었으며 , 두 개의 활성 세션을 갖는 위험을 제거하기 위해 나중에 세션을 실제로 제거해야한다고 결정했습니다.
또한 함수는 더 이상 실제로 토큰을 반환하지 않고 대신 영구 데이터 내에 저장합니다. 따라서 나중에 공용 함수 getAccessToken을 사용하여 새 액세스 토큰을 얻을 수 있습니다 . 공식 Facebook PHP SDK github 페이지 에서 새 SDK를 가져 와서 최신 상태인지 확인하세요.

원래 답변 :

60 일 후에 만료되는 새 액세스 토큰을 반환하는 새로운 공용 함수를 base_facebook.php 파일에 추가했습니다. 일반 액세스 토큰을받은 후이 함수를 요청할 수 있습니다. 테스트하지는 않았지만 개발자 앱의 고급 설정에서 'deprecate offline_access'를 활성화해야한다고 가정합니다.

facebook 클래스 내부의 base_facebook.php에 이것을 추가하고 호출하십시오. 그것은 나를 위해 작동합니다.

 public function getExtendedAccessToken(){

    try {
        // need to circumvent json_decode by calling _oauthRequest
          // directly, since response isn't JSON format.
        $access_token_response =
            $this->_oauthRequest(
                $this->getUrl('graph', '/oauth/access_token'), array(
                    'client_id' => $this->getAppId(),
                    'client_secret' => $this->getAppSecret(),
                    'grant_type'=>'fb_exchange_token',
                    'fb_exchange_token'=>$this->getAccessToken()
                )
            );
    } catch (FacebookApiException $e) {
      // most likely that user very recently revoked authorization.
      // In any event, we don't have an access token, so say so.
      return false;
    }

    if (empty($access_token_response)) {
      return false;
    }

    $response_params = array();
    parse_str($access_token_response, $response_params);
    if (!isset($response_params['access_token'])) {
      return false;
    }

    return $response_params['access_token'];
}

실제로 말한 내용 :

access_token이 서버 측 OAuth 호출에서 생성 된 경우 결과 access_token의 만료 시간이 더 길어집니다 . 해당 사용자에 대한 유효한 access_token이있는 동안 호출이 이루어지면이 두 번째 호출에서 반환 된 access_token은 동일하게 유지되고 만료 시간 만 연장됩니다. 다시 말하지만 같은 날에 이것을 여러 번 호출하면 첫 번째 호출에서만 만료 시간이 연장됩니다.

즉, 클라이언트 측에서 생성 한 토큰보다 길고 확장 토큰 (60 일)을 받으려면 다음 요청을 통해 수동으로 수행해야합니다.

https://graph.facebook.com/oauth/access_token?             
    client_id=APP_ID&
    client_secret=APP_SECRET&
    grant_type=fb_exchange_token&
    fb_exchange_token=EXISTING_ACCESS_TOKEN

이 토큰은 여러 가지 이유로 여전히 유효하지 않을 수 있으며,이를 처리하는 방법은 방법 : 만료 된 액세스 토큰 처리 블로그 게시물에 설명되어 있습니다.

업데이트 :
바와 같이의 2012년 8월 7일 사용할 수있는 setExtendedAccessToken확장하는 방법을 access_token대신 수동으로 URL을 구성하고 세부 사항을 검색의.


// 페이스 북 로그인 팝업에 자바 스크립트 사용

FB.login(function(response) {

            if (response.authResponse) {

                   var accessToken = response.authResponse.accessToken;

// 만료 시간이 1-2 시간 인 액세스 토큰을 얻었습니다.

// 페이스 북 컨트롤러라는 컨트롤러에 액세스 토큰을 가져 왔습니다.

        $request = $this->getRequest();
        $params = $request->getParams();
        $token=$params['accessToken'];

// 액세스 토큰을 받아 60 일까지 연장

        $conf = $this->getConfigs();
        $appid = $conf['fbdetails']['appid'];
        $secret = $conf['fbdetails']['secret'];
        $baseurl = $conf['app']['baseurl'];

// 아래 코드 실행 후 acess 토큰 만료 시간이 60 일인 응답을 받게됩니다.

        $token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$appid."&client_secret=".$secret."&grant_type=fb_exchange_token&fb_exchange_token=".$token;

// 위의 응답은 구문 분석을 위해 제공됩니다.

        $c = curl_init();
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($c, CURLOPT_URL, $token_url);
        $contents = curl_exec($c);
        $err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
        curl_close($c);

        $paramsfb = null;
        parse_str($contents, $paramsfb);

// 위 실행 코드의 내용을 구문 분석 한 후 새로운 확장 액세스 토큰이 저장됩니다.

        $user_session = new Zend_Session_Namespace('fbuser');
        $user_session->access_token = $paramsfb['access_token'];

// 세션에 저장됩니다.

        $this->_redirect('/home');

// 좋은 코딩


서버 측 OAuth 호출을 통해 생성 된 액세스 토큰은 확장 된 (더 긴) 종류이므로 교환 할 필요가 없습니다. 이미 확장 된 토큰입니다. 앱 설정에서 '오프라인 액세스 사용 중지'를 사용 설정하면됩니다. 물론 이것은 "오프라인 액세스 사용 중지"가 이전에 비활성화 된 경우에만 필요합니다.

그런 다음 Facebook을 통해 사용자를 인증하면 60 일 동안 유지되는 액세스 토큰을 받게됩니다. 같은 날에 여러 번 인증하면 첫 번째 인증에서만 만료 시간이 연장됩니다.


것을 토큰 당신은 액세스를 필요로해야 NEVER는 A에 대한 만료 PAGE , 비슷한 질문에 대한 내 대답을 참조 여기에

개발자 페이지에서 :

수명이 긴 사용자 액세스 토큰을 사용하여 [사용자 ID] / 계정 끝점을 쿼리하면 사용자가 관리하는 페이지에 대해 만료되지 않는 페이지 액세스 토큰제공 됩니다 .


이는 페이지 액세스 토큰을 만료되지 않음으로 연장하고 2 개월 후 만료되는 사용자 액세스 토큰 ( '새 액세스 토큰')의 수명을 연장하기위한 것입니다.

좋아, 약 일주일의 연구가 걸렸지 만 여기에 내 해결책이 있습니다. https://developers.facebook.com/tools/explorer/ 에서 access_token의 일부로 manage_page가 있는지 확인하십시오. 그런 다음 앱 ID, 암호 및 리디렉션과 함께이 코드를 사용합니다.

<?php
   app_id = "APP_ID";
   $app_secret = "APP_SECERET";
   $post_login_url = "REDIRECT_URL";


   $code = $_REQUEST['code'];

   //Obtain the access_token with publish_stream permission 
   if(empty($code)){ 
      $dialog_url= "http://www.facebook.com/dialog/oauth?"
       . "client_id=" .  $app_id 
       . "&redirect_uri=" . urlencode( $post_login_url)
       .  "&COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES";
      echo("<script>top.location.href='" . $dialog_url 
      . "'</script>");
     }
    else {


      $token_url="https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id 
       . "&redirect_uri=". urlencode($post_login_url)
       . "&client_secret=" . $app_secret
       . "&code=" . $code;
      $response = file_get_contents($token_url);
      $params = null;
      parse_str($response, $params);
      $access_token = $params['access_token'];
      echo 'access token: ' . $access_token.'<br>';

        if($access_token){


          $token_url="https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id 
       . "&redirect_uri=". urlencode($post_login_url)
       . "&client_secret=" . $app_secret
       .'&grant_type=fb_exchange_token'
       . "&fb_exchange_token=" . $access_token;
       $response = file_get_contents($token_url);
       $access_token = $params['access_token'];
       echo 'new access token: '.$access_token;

        }
    }*/

?>

After that copy the 'new access token' and go back to https://developers.facebook.com/tools/explorer/ When you get there past in your new access token into the the access token field. Then click submit. After that in the node you will see a +____ click on this and scroll down to the accounts and click that. find the page that you need the access token for and copy and paste it into the access key field. click debug and you will see that it will never expire. save that token it will stay valid as long as you do not reset your apps secret.


Inspired by previous answers, I wrote a simple token self-renewal program. First, just put your current token in the 'token.sec' file.

This program will read a token from the file, and update with a new token if everything is OK. In other programs, you just need to use the token:

$access_token = file_get_contents("token.sec");

Here we are:

<?php
$app_id = "<your app id>";
$app_secret = "<your app secret>";
$access_token = file_get_contents("token.sec");

$token_url="https://graph.facebook.com/oauth/access_token?"
   . "grant_type=fb_exchange_token"
   . "&client_id=" . $app_id 
   . "&client_secret=" . $app_secret
   . "&fb_exchange_token=" . $access_token;

$ch = curl_init($token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch); 
if($response === false) {
    die ('Curl error: ' . curl_error($ch));
}

// Close handle
curl_close($ch);

// parse the output
parse_str($response, $params);
if(!isset($params['access_token'])) {
    die("No access token");
}

echo ("New token: $access_token\n");

// eveything looks OK
rename("token.sec", "token.sec.back"); // just in case
$myfile = fopen("token.sec", "w") or die("Unable to open file!");
fwrite($myfile, $access_token);
fclose($myfile);
?>

Finally, we can add this in our crontab to renew the token once per momth:

0 0 1 * * cd /home/<path>; php exchangeToken.php

참고URL : https://stackoverflow.com/questions/8982025/how-to-extend-access-token-validity-since-offline-access-deprecation

반응형