새로 고침 토큰을 사용하여 백그라운드에서 인증을 받고 액세스 토큰을 얻는 방법은 무엇입니까? (How to use refresh token to get authorized in background and getting access token?)


문제 설명

새로 고침 토큰을 사용하여 백그라운드에서 인증을 받고 액세스 토큰을 얻는 방법은 무엇입니까? (How to use refresh token to get authorized in background and getting access token?)

refreshToken을 사용하여 accessToken을 얻으려고 합니다. 아래에 제 코드를 게시했습니다. 누군가 안내해 주세요.

이는 내가 개발 중인 WordPress 플러그인에서 가져온 것이므로 pageViews 및 pagePath만 검색하면 되므로 그렇지 않습니다. 사용 가능한 플러그인 사용을 선호합니다.

OAuth 갱신 토큰을 사용하여 새 액세스 토큰 얻기 ‑ Google API

 if( isset( $this‑>options['authenication_code'] ) ){   //plugin setting page settings 
                global $wpdb;
                $resultset = $wpdb‑>get_row( 'SELECT `refreshToken` FROM ' . $wpdb‑>prefix . 'analyticaAnalytics WHERE authenication_code ="' . $this‑>options["authenication_code"] . '"', ARRAY_A );
                var_dump( $resultset['refreshToken'] ); //retrieved refreshToken from database
                if ($client‑>isAccessTokenExpired()) {              //boolean true
                    $client‑>refreshToken( $resultset['refreshToken'] ); 
                    var_dump( $client );//getting blank
                }
            }

../google‑api‑php‑client/src/Google/Auth/ oauth2.php

private function refreshTokenRequest($params)
  { 
    if (isset($params['assertion'])) {

      $this‑>client‑>getLogger()‑>info(
          'OAuth2 access token refresh with Signed JWT assertion grants.'
      );
    } else {
        $this‑>client‑>getLogger()‑>info('OAuth2 access token refresh');
    }

    $http = new Google_Http_Request(
        self::OAUTH2_TOKEN_URI,
        'POST',
        array(),
        $params
    );

    $http‑>disableGzip();
    $request = $this‑>client‑>getIo()‑>makeRequest($http);
    //var_dump( $request );exit;//response 400, invalid grant
    $code = $request‑>getResponseHttpCode();

    $body = $request‑>getResponseBody();
    if (200 == $code) {
      $token = json_decode($body, true);
      if ($token == null) {
        throw new Google_Auth_Exception("Could not json decode the access token");
      }

      if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
        throw new Google_Auth_Exception("Invalid token format");
      }

      if (isset($token['id_token'])) {
        $this‑>token['id_token'] = $token['id_token'];
      }
      $this‑>token['access_token'] = $token['access_token'];
      $this‑>token['expires_in'] = $token['expires_in'];
      $this‑>token['created'] = time();
    } else {
      throw new Google_Auth_Exception("Error refreshing the OAuth2 token, message: '$body'", $code);
    }
  }

많은 시간을 보낸 후 $request = $this‑>client‑>getIo()‑>에 대한 응답 코드 400 오류가 발생했습니다. makeRequest($http);이는 잘못된 권한입니다.

전체 코드


참조 솔루션

방법 1:

This is how , I solved the problem, We need to store the refreshToken in our database and using that refreshToken, We can get another accessToken .which can be used to get the result and it does not need another authentication .

<?php
        $client = new Google_Client();
        $client‑>setAuthConfigFile(plugin_dir_url( __FILE__ ) . '/client_secrets.json');
        $client‑>setRedirectUri( site_url() . '/wp‑admin/admin.php?page=analytica‑admin‑settings');
        $client‑>addScope(Google_Service_Analytics::ANALYTICS_READONLY);
        $client‑>setIncludeGrantedScopes(true);
        $client‑>setAccessType('offline');
        if ( isset( $_GET['code'] )) {

            if($client‑>isAccessTokenExpired()){

                $client‑>authenticate($_GET['code']);

                $accessToken = $client‑>getAccessToken();
                $refreshToken = $client‑>getRefreshToken();

                $analytica_tokens = json_encode( array( 'time' => current_time( 'mysql' ),'accessToken' =>  $accessToken, 'refreshToken' => $refreshToken ) );
                update_option( 'analytica_tokens', $analytica_tokens );
            } 
        } else {
            $resultset = json_decode(get_option('analytica_tokens'));

            if ($client‑>isAccessTokenExpired()) {
                if( isset( $resultset ) ){
                    $refreshToken = $resultset‑>refreshToken;
                    $client‑>refreshToken( $refreshToken );
                    $accessToken = $client‑>getAccessToken();           
                    $analytica_tokens = json_encode( array( 'time' => current_time( 'mysql' ), 'accessToken' =>  $accessToken, 'refreshToken' => $refreshToken ) );
                    update_option( 'analytica_tokens', $analytica_tokens );
                } else {
                    echo 'You need to reauthorize the application to get the analytics report.';
                }
            }
        }
        $auth_url = $client‑>createAuthUrl();
        ?>
         <a class="connect‑to‑google‑analytics" href='<?php echo $auth_url; ?>'  id="loginText">Connect To Your Google Analytics Account </a>
        <?php
        if( isset($accessToken) ){
            $_SESSION['access_token'] = $accessToken ? $accessToken : $refreshToken;
            $client‑>setAccessToken($_SESSION['access_token']);
            // Create an authorized analytics service object.
            $analytics = new Google_Service_Analytics($client);

            // Get the first view (profile) id for the authorized user.
            $profile = $this‑>getFirstProfileId($analytics);

            // Get the results from the Core Reporting API and print the results.
            $this‑>results = $this‑>getResults($analytics, $profile);
        }
        ?>

(by Prafulla Kumar SahuPrafulla Kumar Sahu)

참조 문서

  1. How to use refresh token to get authorized in background and getting access token? (CC BY‑SA 2.5/3.0/4.0)

#OAuth #google-app-engine #PHP #access-token #wordpress






관련 질문

포도 API 및 OAuth (Grape API and OAuth)

단일 사용자 계정에 대해 동일한 타사 애플리케이션을 여러 번 승인하는 방법은 무엇입니까? (How to handle authorizing the same third-party application multiple times for a single user account?)

Google OAuth의 액세스 토큰 만료 시간대 (Google OAuth's access token's expiry timezone)

Facebook에서 앱 ID를 얻는 방법 (How to get app id on Facebook)

새로 고침 토큰을 사용하여 백그라운드에서 인증을 받고 액세스 토큰을 얻는 방법은 무엇입니까? (How to use refresh token to get authorized in background and getting access token?)

JSON 웹 토큰을 사용하여 Chrome 확장 프로그램에서 내 앱으로 POST 요청을 인증하는 방법은 무엇입니까? (How to authenticate a POST request from a chrome extension to my app with JSON web tokens?)

LAN 내부에 인증 자동 기능이 있는 Grails 애플리케이션을 테스트할 수 없습니다. (Cannot test Grails application which has oauth autontication inside LAN)

신뢰할 수 없는 호스트를 사용하여 방화벽에서 보안 연결을 중개하는 방법은 무엇입니까? (How to broker secure connection across firewalls using untrusted host?)

로컬 HTML 파일에서 oAuth 흐름을 처리합니까? (Handling an oAuth flow from local HTML files?)

Twitter4J로 인증하는 방법은 무엇입니까? (how to authenticate with Twitter4J?)

IdentityServer4를 사용할 때 "코드 챌린지 필요" 메시지가 나타납니다. (I am getting "code challenge required" when using IdentityServer4)

Apache Superset 및 Auth0은 "브라우저(또는 프록시)가 이 서버가 이해할 수 없는 요청을 보냈습니다."를 반환합니다. (Apache Superset and Auth0 returns "The browser (or proxy) sent a request that this server could not understand.")







코멘트