在過去的幾天中,我花了一些時間試圖爲我的Web應用程序實現一個功能。該功能應該在脫機時將新事件添加到用戶的Google日曆中。我閱讀了有關Web服務器應用程序的Google OAuth2文檔,並且似乎瞭解它的基本知識。我創建了一個鏈接到授權脫機訪問應用程序:DotNetOpenAuth Google API脫機訪問
<a target='_blank' href='https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ftasks&response_type=code&client_id=<MY CLIENT ID>&access_type=offline&redirect_uri=http%3A%2F%2Flocalhost:49949%2Foauth2callback.aspx'>Grant Tasks Permission</a>
如果用戶接受,然後我抓住了刷新令牌的重定向URI是這樣的:
private static OAuth2Authenticator<WebServerClient> _authenticator;
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Request["code"] != null)
{
_authenticator = CreateAuthenticator();
_authenticator.LoadAccessToken();
}
Response.Write("Refresh Token: " + _authenticator.State.RefreshToken);
}
private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
{
var provider = new WebServerClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = "<MY CLIENT ID>";
provider.ClientSecret = "<MY CLIENT SECRET>";
return new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization);
}
private IAuthorizationState GetAuthorization(WebServerClient client)
{
return client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
}
出於測試目的,我一直在複製刷新令牌到文本文件供進一步使用。
我的問題是使用此刷新令牌進行訪問。我一直在用這個代碼來刷新令牌:
protected void btnGetTasks_Click(object sender, EventArgs e)
{
if (_service == null)
{
_authenticator = CreateAuthenticator();
_service = new TasksService(new BaseClientService.Initializer() { Authenticator = _authenticator });
}
var cl = _service.Tasklists.List().Fetch();
}
private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
{
// Register the authenticator.
var provider = new WebServerClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = "<MY CLIENT ID>";
provider.ClientSecret = "<MY CLIENT SECRET>";
var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization);
return authenticator;
}
private IAuthorizationState GetAuthorization(WebServerClient client)
{
string scope = "https://www.googleapis.com/auth/tasks";
IAuthorizationState state = new AuthorizationState(new[] { scope });
state.RefreshToken = "<REFRESH TOKEN FROM FIRST STEP>";
var result = client.RefreshToken(state);
return client.ProcessUserAuthorization();
}
在這一點上一切似乎都很好。當我遍歷代碼時,我可以看到client.RefreshToken(state)的結果是true。問題是當我打電話給這行代碼:
_service.Tasklists.List().Fetch();
它從谷歌返回(401)未經授權的錯誤。我正在尋找原因,但我不知道如何繼續,而且我使用此功能的時間不足。任何建議將不勝感激。謝謝!