谷歌“Oauth 2.0 for login”的回复在授权后丢失了电子邮件

时间:2014-09-11 02:26:24

标签: google-oauth

我正在尝试使用Oauth 2.0进行登录,但以下代码未产生一致的响应。为什么?电子邮件“有时”出现,但我在这里找不到任何可以解释各种反应的内容。这里的目标是我可以使用电子邮件在我的系统中查找用户。

<?php

// http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
require_once 'sites/all/modules/schoology_core/s_support/JWT.php';

// app info (see google api console for creds)
$google_client_id = '';
$google_secret = '';
$google_redirect_uri = '';
$google_is_auth_response = (isset($_GET['code']) || isset($_GET['error']));

// construct auth url used to redirect user to google login form
$auth_url  = 'https://accounts.google.com/o/oauth2/auth?';
$auth_url .= 'client_id=' . $google_client_id . '&';
$auth_url .= 'response_type=code&';
$auth_url .= 'scope=openid%20email&';
$auth_url .= 'redirect_uri=' . $google_redirect_uri . '&';
$auth_url .= 'state=' . uniqid();
$auth_link = '<br><a href="'. $auth_url .'">'. $auth_url .'</a>';

// send user to google login form
if(!$google_is_auth_response) {
 print $auth_link;
 exit;
}

// handle response
if($_GET['error']) {
 print 'Oauth2 response error=' . $_GET['error'];
}
else {
 // exchange one-time authorization code for access token and ID token
 $curl = curl_init();
 curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://accounts.google.com/o/oauth2/token',
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_POST => TRUE,
  CURLOPT_POSTFIELDS => array(
    'code' => $_GET['code'],
    'client_id' => $google_client_id,
    'client_secret' => $google_secret,
    'redirect_uri' => $google_redirect_uri,
    'grant_type' => 'authorization_code',
   )
  ));
  $response = curl_exec($curl);
  $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  curl_close($curl);

  // decode response and id token to retrieve user's email
  $response = json_decode($response);
  $jwt_id_token = JWT::decode($response->id_token, NULL, FALSE);
  $response_info = print_r(array(
   'auth_code' => $_GET['code'],
   'response_code' => $responseCode,
   'response_decoded' => $response,
   'id_token' => $jwt_id_token,
   'email_is_not_preset' => $jwt_id_token->email ? 'Y' : 'N'
   ), TRUE);
   print '<pre>' . $response_info . '</pre>';
 }

0 个答案:

没有答案