我有一个google访问令牌,注册了gmail api和google contacts api的范围。我这样做了:
var code = Request.QueryString["code"];
OAuth2Parameters parameters = new OAuth2Parameters()
{
ClientId = clientId,
ClientSecret = clientSecret,
RedirectUri = redirectUri,
Scope = scopes
};
if (code == null)
{
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
return Redirect(url);
}
parameters.AccessCode = code;
OAuthUtil.GetAccessToken(parameters);
现在我需要通过gmail api发送电子邮件。但在谷歌文档中我发现只有一种方法可以在gmail api中使用UserCredential进行身份验证:
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
但我已经有了工作访问令牌,我怎么用它来发送电子邮件?
答案 0 :(得分:2)
https://github.com/google/google-api-dotnet-client/issues/761
看起来你使用了我做的相同的例子,当你交换代码以获得需要传递给UserCredential对象的构造函数的流的令牌响应时,结果证明了。
var clientSecrets = new ClientSecrets { ClientId = clientId, ClientSecret = secret };
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = clientSecrets,
Scopes = new[] { @"https://www.googleapis.com/auth/gmail.settings.basic" }
});
TokenResponse token = await flow.ExchangeCodeForTokenAsync("userEmail", authCode, "http://localhost:30297", CancellationToken.None);
UserCredential cred = new UserCredential(flow, "me", token);
string accessToken = token.AccessToken;
var service = new GmailService(
new BaseClientService.Initializer { HttpClientInitializer = cred });
答案 1 :(得分:0)
据我所知,.NET客户端不允许您从现有的访问令牌创建UserCredential对象。而是使用库提供的授权流程并使用它们生成正确的对象。