문제

안녕하세요. 여기에서 뭔가를 배우고 싶습니다. 기본적으로 내 시스템에 대한 액세스가 Google 계정에 있도록 하고 싶습니다. 어떻게든 다음을 수행할 수 있습니다.

  • 클라이언트 ID 가져오기, URI 리디렉션, 비밀 키
  • 구글 계정으로 인증
  • 토큰을 얻다

하지만 나는 내가 어떤 부분에서 잘못하고 있다고 느꼈습니다. Oauth2callback

class Oauth2callback extends CI_Controller {


    function __construct(){
        parent::__construct();

        $this->load->helper('url');
        $this->load->library('session');
        require_once APPPATH.'libraries/Google/Client.php';
        session_start();


    }

    public function index()
    {


        $client_id = $this->config->item('client_id');
        $client_secret = $this->config->item('client_secret');
        $redirect_uri = $this->config->item('redirect_uri');

        $client = new Google_Client();
        $client->setClientId($client_id);
        $client->setClientSecret($client_secret);
        $client->setRedirectUri($redirect_uri);
        $client->addScope("https://www.googleapis.com/auth/userinfo.email");
        $client->addScope("https://www.googleapis.com/auth/userinfo.profile");

        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
            $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

            header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
        }

        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
            $client->setAccessToken($_SESSION['access_token']);
        } else {
            $authUrl = $client->createAuthUrl();
        }

        if ($client->getAccessToken()) {
            $_SESSION['access_token'] = $client->getAccessToken();


        }


        if(isset($authUrl)) {
            header('location:'. base_url());
        }else{
            header('location:'. base_url().'dashboard');
        }
    }

하지만 이건 내 인덱스 컨트롤러야 Login 버튼만 있어요 sign in with Google

class Login extends CI_Controller {


    function __construct(){
        parent::__construct();

        $this->load->helper('url');
        $this->load->library('session');
        require_once APPPATH.'libraries/Google/Client.php';
        session_start();
    }

    public function index()
    {
        //$this->checkSession();
        $client_id = $this->config->item('client_id');
        $client_secret = $this->config->item('client_secret');
        $redirect_uri = $this->config->item('redirect_uri');

        $client = new Google_Client();
        $client->setClientId($client_id);
        $client->setClientSecret($client_secret);
        $client->setRedirectUri($redirect_uri);
        $client->addScope("https://www.googleapis.com/auth/userinfo.email");
        $client->addScope("https://www.googleapis.com/auth/userinfo.profile");

            $authUrl = $this->data['authUrl'] = $client->createAuthUrl();
            $this->load->view('login/index.php',$this->data);
            $this->load->view('template/pre_footer');
            $this->load->view('template/footer');


    }
}


MVC PHP를 사용하는 올바른 프로세스는 무엇입니까? ff를 수행해야 합니다.:
ㅏ.버튼을 클릭하세요 sign in to google
비.토큰을 가져와 세션에 저장
씨.내 전체 시스템(모든 컨트롤러에서)에 토큰을 사용했습니다.

지금 내가 가지고 있는 것은 A & B인데 C는 어떻게 해야할지 전혀 모르겠습니다.

누구든지 이것으로 나를 도울 수 있습니까?어떤 제안 의견이라도 높이 평가됩니다.미리 감사드립니다.

도움이 되었습니까?

해결책

귀하가 가지고 있는 코드는 인증 URL, Google로 리디렉션, 사이트 콜백 및 액세스 토큰 저장을 동시에 처리하기 때문에 다소 혼란스러울 수 있습니다.

액세스 토큰을 사용하여 API에 대한 인증된 호출을 수행하는 경우 훨씬 간단합니다.세션에 유효한 액세스 토큰이 저장되어 있으면 다음과 같이 어디에서나 이를 사용하여 Google 애플리케이션을 초기화할 수 있습니다.

// client
$client = new Google_Client();
$client->setApplicationName('Google Application');
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);

// token
$client->setAccessToken($token);

이제 이 기능을 여러 컨트롤러에서 사용할 수 있게 하려면 CodeIgniter에서 가장 적절한 방법은 위의 코드를 래핑하는 새 라이브러리를 만드는 것입니다.

라이브러리 사용의 장점은 CodeIgniter 구성에서 자동으로 로드될 수 있고 코드 어디에서나 쉽게 액세스할 수 있다는 것입니다.

예제 라이브러리:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Someclass {

    private $client;

    public function __construct()
    {
        ... 

        // client
        $client = new Google_Client();
        $this->client->setApplicationName('Google Application');
        $this->client->setClientId($clientId);
        $this->client->setClientSecret($clientSecret);
        $this->client->setRedirectUri($redirectUri);

        // token
        $this->client->setAccessToken($token);
    }
}

?>

그런 다음 컨트롤러에서 사용하려면 다음을 수행하면 됩니다.

 $this->load->library('someclass');

특정 API에 대한 바로가기를 만들 수도 있습니다.예를 들어, Google Analytics API에 빠르게 액세스하려면 다음을 수행할 수 있습니다.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Someclass {

    private $client;

    public function __construct()
    {
        ... 

        // client
        $client = new Google_Client();
        $this->client->setApplicationName('Google Application');
        $this->client->setClientId($clientId);
        $this->client->setClientSecret($clientSecret);
        $this->client->setRedirectUri($redirectUri);

        // token
        $this->client->setAccessToken($token);
    }

    public function analytics()
    {
        return new Google_Service_Analytics($this->client);
    }
}

?>

그런 다음 컨트롤러에서 다음과 같이 사용하십시오.

 $this->load->library('someclass');
 $this->someclass->analytics();

CodeIgniter 라이브러리에 대해 자세히 알아보세요.

http://ellislab.com/codeigniter/user-guide/general/creating_libraries.html

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top