使用 .Net 和 OAuth 2.0 的 Google Apps Email Settings API



我想使用电子邮件设置 API,但找不到任何文档如何将此 API 与 oAuth2 身份验证一起使用

  1. 我是否使用了正确的 API?
  2. 我是否正在使用最新的 API?(Google.GData.Apps.dll版本2.2.0(
  3. 如何将此 DLl 与带有 p12 文件的谷歌控制台项目一起使用和服务帐户?

根据Google文档,这是最新的api voor电子邮件设置:https://developers.google.com/admin-sdk/email-settings/

我在此页面上找不到任何有关如何在 .Net 中使用 Oauth 的文档,但在示例中我看到以下内容:

using Google.GData.Apps;
using Google.GData.Apps.GoogleMailSettings;
GoogleMailSettingsService service = new GoogleMailSettingsService("yourdomain", "your-apps");
service.setUserCredentials("adminUsername", "adminPassword");    
service.CreateSendAs("liz", "Sales", "sales@example.com", "", "true");

因此,搜索这些参考资料,我找到了此页面:https://code.google.com/p/google-gdata/或 nuget 包:www.nuget.org/packages/Google.GData.Apps/最新版本是 2.2.0

由于我们使用控制台项目 Oauth2 和服务帐户切换到新的 api,我的问题是,我是否可以使用 dll 也使用与最新 API 相同的身份验证

新 API 使用以下身份验证方法:

X509Certificate2 certificate = new X509Certificate2(@"locationP12File.p12", "notasecret", X509KeyStorageFlags.Exportable);
IEnumerable<string> scopes = new[] { DirectoryService.Scope.AdminDirectoryUser, DirectoryService.Scope.AdminDirectoryUserSecurity };
ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer("ServiceAccountEmail@domain.com")
    {
        Scopes = scopes,
        User = "AdminAccount@domain.com"
    }.FromCertificate(certificate));
// Create the service.
var service = new DirectoryService(
    new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "Admin directory Provisioning Sample",
    });
service.Users.Delete(userKey).Execute();

对于电子邮件设置 API 和任何其他作为服务的 GData 类,可以使用如下所示的内容:

using Google.GData.Apps;
using Google.GData.Apps.GoogleMailSettings;
using Google.GData.Client;
// Name of my cli application
string applicationName = "Test-OAuth2";
// Installed (non-web) application
string redirectUri = "urn:ietf:wg:oauth:2.0:oob";
// Requesting access to Contacts API and Groups Provisioning API
string scopes = "https://apps-apis.google.com/a/feeds/emailsettings/2.0/";
// Stuff usually found on client_secrets.json
string clientId = CLIENT_ID;
string clientSecret = CLIENT_SECRET;
string domain = CLIENT_DOMAIN;
// Prepare OAuth parameters
OAuth2Parameters parameters = new OAuth2Parameters() {
    ClientId = clientId,
    ClientSecret = clientSecret,
    RedirectUri = redirectUri,
    Scope = scopes
};
// Request authorization from the user
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
Console.WriteLine("Authorize URI: " + url);
// Fetch the access code from console
parameters.AccessCode = Console.ReadLine();
// Get an access token
OAuthUtil.GetAccessToken(parameters);
try {
    // Create a new request factory so it uses our OAuth credentials
    GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory("apps", applicationName, parameters);
    GoogleMailSettingsService service = new GoogleMailSettingsService(domain, applicationName);
    service.RequestFactory = requestFactory;
    // Update the signature for the user testUserName
    service.UpdateSignature("test@test.localhost.com", "My tiny signature");
} catch (AppsException a) {
    Console.WriteLine("A Google Apps error occurred.");
    Console.WriteLine();
    Console.WriteLine("Error code: {0}", a.ErrorCode);
    Console.WriteLine("Invalid input: {0}", a.InvalidInput);
    Console.WriteLine("Reason: {0}", a.Reason);
}

可以在此处查看随 GData 提供的 OAuth 示例中的完整示例:https://code.google.com/p/google-gdata/source/browse/trunk/clients/cs/samples/oauth2_sample/oauth2demo.cs

对于使用请求的其他 GData 类,流类似,但改为创建一个 RequestSettings 对象并将其传递到 GData 请求对象构造函数中,如下所示:https://code.google.com/p/google-gdata/source/browse/trunk/clients/cs/samples/oauth2_sample/oauth2demo.cs#63

我以这个示例从目录 API 创建 OAuth 流https://developers.google.com/admin-sdk/directory/v1/quickstart/dotnet 并使用它来连接到电子邮件设置 API 服务。

    static string[] Scopes = { "https://apps-apis.google.com/a/feeds/emailsettings/2.0/" };
        static string ApplicationName = "your-apps";
    static void Main(string[] args)
    {
        UserCredential credential;

        using (var stream =
            new FileStream("../../client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }
        OAuth2Parameters parameter = new OAuth2Parameters()
        {
            AccessToken = credential.Token.AccessToken
        };

        GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory("apps", ApplicationName, parameter);
        GoogleMailSettingsService service = new GoogleMailSettingsService("example.com", ApplicationName);
        service.RequestFactory = requestFactory;

        service.CreateSendAs("liz", "Sales", "sales@example.com", "", "true");
        Console.Read();
    }

相关内容

  • 没有找到相关文章

最新更新