我正在尝试访问Google API v3 Calendarlist,但即使我为用户提供了有效的AccessToken,我仍会收到401/404回复。
(我已完成OAuth2 protocol for Web Server Applications并获得了https://www.googleapis.com/auth/calendar权限)
为此找到好的文档相当困难,谷歌网站本身不是很有帮助,搜索充满了旧的v2信息或使用SDK。通常我可以将python回复转换为c#,但在这种情况下,即使这对我没有帮助。
所以我把头发拉了出去,但我可能会忘记一些非常简单的东西,比如一个缺失的参数或某些东西,所以如果有人快速查看这段代码并告诉我我的内容,我将不胜感激。我做错了。
var applicationKey = moduleModel.Application.Key;
var userID = moduleModel.User.UserID;
var accessToken = moduleModel.User.AccessToken.Token;
// It doesn't seem to make any difference whether I use the querystring
// parameter or the request header to specify the access_token
var sendAccessTokenAsHeader =
!(Request.QueryString["SendAccessTokenAsHeader"] == "0");
// I tried navigating to a specific user but it results in a 404 Not Found
var requestSpecificUserID =
Request.QueryString["RequestSpecificUserID"] == "1";
// Including or omitting my API_KEY doesn't seem to make any difference
var sendApplicationKey =
!(Request.QueryString["SendApplicationKey"] == "0");
var urlBuilder = new System.Text.StringBuilder();
urlBuilder.Append("https://");
urlBuilder.Append("www.googleapis.com");
if (requestSpecificUserID)
{
urlBuilder.Append
(string.Format("/calendar/v3/users/{0}/calendarList", userID));
}
else
{
urlBuilder.Append
("/calendar/v3/users/me/calendarList");
}
var parameterJoiner = "?";
if (sendApplicationKey)
{
urlBuilder.Append
(
string.Format
(
"{0}{1}={2}",
parameterJoiner,
"key",
HttpUtility.UrlEncode(applicationKey)
)
);
parameterJoiner = "&";
}
if (!sendAccessTokenAsHeader)
{
urlBuilder.Append
(
string.Format
(
"{0}{1}={2}",
parameterJoiner,
"access_token",
HttpUtility.UrlEncode(accessToken)
)
);
parameterJoiner = "&";
}
var httpWebRequest = HttpWebRequest.Create(urlBuilder.ToString())
as HttpWebRequest;
httpWebRequest.CookieContainer = new CookieContainer();
if (sendAccessTokenAsHeader)
{
httpWebRequest.Headers["Authorization"] = string.Format
(
"Bearer {0}",
accessToken
);
}
// GetSafeResponse is just an extension method to catch the WebException
// when the HttpStatusCode != OK
var response = httpWebRequest.GetSafeResponse();
// returns 401 (requestSpecificUserID = false)
// or 404 (requestSpecificUserID = true)
var responseText = response.GetResponseText();
return responseText;
提前谢谢!
答案 0 :(得分:1)
我通过阅读this问题找到了答案。
显然,即使Google文档未提及 ,也需要参数 minAccessRole 。
工作示例:
var accessToken = moduleModel.User.AccessToken.Token;
var urlBuilder = new System.Text.StringBuilder();
urlBuilder.Append("https://");
urlBuilder.Append("www.googleapis.com");
urlBuilder.Append("/calendar/v3/users/me/calendarList");
urlBuilder.Append("?minAccessRole=writer");
var httpWebRequest = HttpWebRequest.Create(urlBuilder.ToString())
as HttpWebRequest;
httpWebRequest.CookieContainer = new CookieContainer();
httpWebRequest.Headers["Authorization"] =
string.Format("Bearer {0}", accessToken);
var response = httpWebRequest.GetSafeResponse();
var responseText = response.GetResponseText();
return responseText;