Google API PHP 클라이언트 인증

헬리오 도로

일부 요청을 승인하는 데 문제가 있으며 401 "Invalid Credentials"오류가 발생합니다. 신청 흐름은 다음과 같습니다. 사용자가 Google 로그인 버튼을 사용하여 내 웹 사이트에 로그인합니다. 오프라인 액세스 매개 변수를 사용하고 있으며 세션에 새로 고침 토큰을 저장하고 있습니다. 사용자가 로그인 한 후 YouTube 계정에서 모든 재생 목록 (공개 및 비공개)을 검색하려고합니다.

$client->setScopes('https://www.googleapis.com/auth/youtube.readonly');
if (isset($_SESSION['googletoken']['refresh_token'])){
$client->setAccessToken($_SESSION['googletoken']['refresh_token']);}
$tokenSessionKey = $client->prepareScopes();

$params = [
'maxResults' => 1,
'mine' => true

];

try{

  $queryParams = [
  'maxResults' => 1,
  'mine' => true
];

  $listResponse = $youtube->playlists->listPlaylists('snippet', $queryParams);
DaImTo

새로 고침 토큰으로 액세스 토큰을 설정하고 있습니다.

$ client-> fetchAccessTokenWithRefreshToken ($ client-> getRefreshToken ());

Oauthcallback.php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';

// Start a session to persist credentials.
session_start();

Oauth2Authncation.php

require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    $client = getOauth2Client();

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
return $client;
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function buildClient(){

    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}

/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri(){

    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}


/**
 * Authenticating to Google using Oauth2
 * Documentation:  https://developers.google.com/identity/protocols/OAuth2
 * Returns a Google client with refresh token and access tokens set. 
 *  If not authencated then we will redirect to request authencation.
 * @return A google client object.
 */
function getOauth2Client() {
    try {

        $client = buildClient();

        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }

        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 

            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Google Maps API 용 OVER_QUERY_LIMIT-클라이언트 측에 PHP

분류에서Dev

Google API PHP 클라이언트를 manuplate하는 방법

분류에서Dev

Google API 클라이언트 인터페이스 방법 설명?

분류에서Dev

클라이언트 자바 스크립트 만 사용하는 Google Natural Language API로 간단한 인증

분류에서Dev

PHP의 Google Cloud Storage 클라이언트에 로그인 필요

분류에서Dev

Google 로그인은 안전한가요? (PHP 클라이언트)

분류에서Dev

Google API PHP 클라이언트-캘린더 목록 및 이벤트 검색

분류에서Dev

클라이언트 라이브러리없이 PHP에서 Google Cloud Storage API에 대한 액세스를 승인하는 방법은 무엇입니까?

분류에서Dev

Google API PHP 클라이언트 라이브러리에서 Google_Client.php를 찾을 수 없습니다.

분류에서Dev

Google API 클라이언트 측 사용-API 키는 필수인가요?

분류에서Dev

php.ini 파일없이 google + api php 클라이언트 라이브러리 포함

분류에서Dev

PHP Google Drive API 인증이 필요하지 않습니다.

분류에서Dev

Google Cloud Endpoints Android 클라이언트-인증 오류

분류에서Dev

google-endpoints 교차 클라이언트 인증

분류에서Dev

클라이언트를 통한 RESTful API 인증

분류에서Dev

Django 내부 API 클라이언트 / 서버 인증 여부?

분류에서Dev

인증서를 사용한 Kubernetes API (NodeJS) 클라이언트 인증 실패

분류에서Dev

Google Glass Mirror API 용 PHP 클라이언트 라이브러리의 맞춤 바닥 글

분류에서Dev

PHP 클라이언트 라이브러리가 포함 된 Google Directory API는 403을 제공합니다.

분류에서Dev

Google API의 Analytics 클라이언트 라이브러리 PHP를 Symfony2에 통합

분류에서Dev

Google API PHP 클라이언트 autoload.php가 필요하지만 누락 되었습니까?

분류에서Dev

WSO2 API Manager-API 클라이언트에서 사용자 인증

분류에서Dev

Swagger 기본 인증이 PHP 클라이언트에서 실패 함

분류에서Dev

Huawei AppGallery Connect API-403 클라이언트 토큰 인증 실패

분류에서Dev

웹 API 2 클라이언트 및 사용자 두 부분 인증

분류에서Dev

node.js 클라이언트의 Adobe Analytics Segments API 인증 문제

분류에서Dev

클라이언트 인증서를 사용하여 PHP 호출 SOAP 함수

분류에서Dev

클라이언트 인증서 인증

분류에서Dev

Google API 클라이언트 : 토큰이 취소됨 문제

Related 관련 기사

  1. 1

    Google Maps API 용 OVER_QUERY_LIMIT-클라이언트 측에 PHP

  2. 2

    Google API PHP 클라이언트를 manuplate하는 방법

  3. 3

    Google API 클라이언트 인터페이스 방법 설명?

  4. 4

    클라이언트 자바 스크립트 만 사용하는 Google Natural Language API로 간단한 인증

  5. 5

    PHP의 Google Cloud Storage 클라이언트에 로그인 필요

  6. 6

    Google 로그인은 안전한가요? (PHP 클라이언트)

  7. 7

    Google API PHP 클라이언트-캘린더 목록 및 이벤트 검색

  8. 8

    클라이언트 라이브러리없이 PHP에서 Google Cloud Storage API에 대한 액세스를 승인하는 방법은 무엇입니까?

  9. 9

    Google API PHP 클라이언트 라이브러리에서 Google_Client.php를 찾을 수 없습니다.

  10. 10

    Google API 클라이언트 측 사용-API 키는 필수인가요?

  11. 11

    php.ini 파일없이 google + api php 클라이언트 라이브러리 포함

  12. 12

    PHP Google Drive API 인증이 필요하지 않습니다.

  13. 13

    Google Cloud Endpoints Android 클라이언트-인증 오류

  14. 14

    google-endpoints 교차 클라이언트 인증

  15. 15

    클라이언트를 통한 RESTful API 인증

  16. 16

    Django 내부 API 클라이언트 / 서버 인증 여부?

  17. 17

    인증서를 사용한 Kubernetes API (NodeJS) 클라이언트 인증 실패

  18. 18

    Google Glass Mirror API 용 PHP 클라이언트 라이브러리의 맞춤 바닥 글

  19. 19

    PHP 클라이언트 라이브러리가 포함 된 Google Directory API는 403을 제공합니다.

  20. 20

    Google API의 Analytics 클라이언트 라이브러리 PHP를 Symfony2에 통합

  21. 21

    Google API PHP 클라이언트 autoload.php가 필요하지만 누락 되었습니까?

  22. 22

    WSO2 API Manager-API 클라이언트에서 사용자 인증

  23. 23

    Swagger 기본 인증이 PHP 클라이언트에서 실패 함

  24. 24

    Huawei AppGallery Connect API-403 클라이언트 토큰 인증 실패

  25. 25

    웹 API 2 클라이언트 및 사용자 두 부분 인증

  26. 26

    node.js 클라이언트의 Adobe Analytics Segments API 인증 문제

  27. 27

    클라이언트 인증서를 사용하여 PHP 호출 SOAP 함수

  28. 28

    클라이언트 인증서 인증

  29. 29

    Google API 클라이언트 : 토큰이 취소됨 문제

뜨겁다태그

보관