未经授权的401 Oauth 2.0 google

时间:2012-01-19 03:08:17

标签: php curl oauth google-api

我在使用Oauth 2.0在gmail中阅读我的收件箱时遇到了麻烦。我将此作为我的范围:https://mail.google.com/mail/feed/atom/

这是我的非工作代码

$fields=array(
    'code'=>  urlencode($authcode),
    'client_id'=>  urlencode($clientid),
    'client_secret'=>  urlencode($clientsecret),
    'redirect_uri'=>  urlencode($redirecturi),
    'grant_type'=>  urlencode('authorization_code')
);

$fields_string='';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string=rtrim($fields_string,'&');

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch,CURLOPT_POST,5);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);

$response=  json_decode($result);
$accesstoken= $response->access_token;

$xmlresponse= file_get_contents('https://mail.google.com/mail/feed/atom/?oauth_token='.$accesstoken);

我甚至得到了我的访问令牌,但仍然没有运气,获得了401未授权错误。

1 个答案:

答案 0 :(得分:1)

https://mail.google.com/mail/feed/atom/不是作为服务器端点的范围,您可以从中获取Feed。请参阅doc。这是Vb.net中的工作代码

objClient.Credentials = New System.Net.NetworkCredential(username, password)
Dim nodelist As XmlNodeList
Dim node As XmlNode
Dim response As String
Dim xmlDoc As New XmlDocument

'get emails from gmail
response = Encoding.UTF8.GetString(objClient.DownloadData("https://mail.google.com/mail/feed/atom"))
response = response.Replace("<feed version=""0.3"" xmlns=""http://purl.org/atom/ns#"">", "<feed>")

'Get the number of unread emails
xmlDoc.LoadXml(response)
node = xmlDoc.SelectSingleNode("/feed/fullcount")
mailCount = node.InnerText
nodelist = xmlDoc.SelectNodes("/feed/entry")
node = xmlDoc.SelectSingleNode("title")

使用PHP和客户端登录

<?php
    $mailbox = imap_open("{imap.googlemail.com:993/ssl}INBOX", "USERNAME@googlemail.com", "PASSWORD");
    $mail = imap_search($mailbox, "ALL");
    $mail_headers = imap_headerinfo($mailbox, $mail[0]);
    $subject = $mail_headers->subject;
    $from = $mail_headers->fromaddress;
    imap_setflag_full($mailbox, $mail[0], "\\Seen \\Flagged");
    imap_close($mailbox);
?>

我不知道如何使用OAuth2.0执行此操作,或者根本无法使用OAuth 2.0获取Feed。