首先,您需要从浏览器提示中获取访问令牌,然后将其保存在某个存储中。
检查令牌是否过期,然后尝试刷新它。
代码如下:
private static IAuthorizationState GetAuthentication(NativeApplicationClient arg)
{
try
{
// Get the auth URL:
var config = new Configuration();
var calendarScope = Google.Apis.Util.Utilities.ConvertToString(CalendarService.Scopes.Calendar);
IAuthorizationState state = new AuthorizationState(new[] { calendarScope });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
var authCode = String.Empty;
if (String.IsNullOrWhiteSpace(config.AccessToken) || config.AccessTokenExpirationTime < DateTime.Now || String.IsNullOrWhiteSpace(config.RefreshToken))
{
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
do
{
authCode = Prompt.ShowDialog("Test", "123");
} while (String.IsNullOrWhiteSpace(authCode));
state = arg.ProcessUserAuthorization(authCode, state);
}
else
{
state.AccessToken = config.AccessToken;
state.AccessTokenExpirationUtc = config.AccessTokenExpirationTime;
state.AccessTokenIssueDateUtc = config.AccessTokenIssueTime;
state.RefreshToken =config.RefreshToken ;
if (state.AccessTokenExpirationUtc < DateTime.Now)
{
var tokenRefreshed = arg.RefreshToken(state);
if (tokenRefreshed)
{
config.AccessToken = state.AccessToken;
config.AccessTokenExpirationTime = state.AccessTokenExpirationUtc;
config.AccessTokenIssueTime = state.AccessTokenIssueDateUtc;
config.RefreshToken = state.RefreshToken;
arg.ProcessUserAuthorization(authCode, state);
}
else
{
throw new ApplicationException("Unable to refresh the token.");
}
}
}
return state;
}
catch (System.Exception exp)
{
throw new ApplicationException("Failed to get authorisation from Google Calender.", exp);
}
}
NativeApplicationClient arg
参数是什么?在我的情况下,我正在使用 GMail.Send 范围。我将令牌文件存储在用户应用程序数据文件夹中。我是否仍然可以使用这种方法? - Andrew Truckle