-
Notifications
You must be signed in to change notification settings - Fork 355
/
Oauth2Authentication.cs
170 lines (159 loc) · 10.2 KB
/
Oauth2Authentication.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Copyright 2017 DAIMTO : www.daimto.com
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: Oauth.tt
// Build date: 01/02/2017 22:32:59
// C# generater version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Gmail v1 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Access Gmail mailboxes including sending user email.
// API Documentation Link https://developers.google.com/gmail/api/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Gmail/v1/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Gmail.v1/
// Install Command: PM> Install-Package Google.Apis.Gmail.v1
//
//------------------------------------------------------------------------------
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;
namespace GoogleSamplecSharpSample.Gmailv1.Auth
{
public static class Oauth2Example
{
/// <summary>
/// This method requests Authentcation from a user using Oauth2.
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static GmailService AuthenticateOauth(string clientSecretJson, string userName)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
string[] scopes = new string[] { GmailService.Scope.GmailSettingsSharing, //Manage your sensitive mail settings, including who can manage your mail
GmailService.Scope.GmailSettingsBasic, //Manage your basic mail settings
GmailService.Scope.GmailMetadata, //View your email message metadata such as labels and headers, but not the email body
GmailService.Scope.GmailReadonly, //View your emails messages and settings
GmailService.Scope.GmailCompose, //Manage drafts and send emails
GmailService.Scope.GmailInsert, //Insert mail into your mailbox
GmailService.Scope.GmailLabels, //Manage mailbox labels
GmailService.Scope.GmailModify, //View and modify but not delete your email
GmailService.Scope.GmailSend, //Send email on your behalf
GmailService.Scope.Https://MailGoogleCom/}; //View and manage your mail
UserCredential credential;
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
return new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Gmail Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
Console.WriteLine("Create Oauth2 account GmailService failed" + ex.Message);
throw new Exception("CreateServiceAccountGmailFailed", ex);
}
}
/// <summary>
/// Authenticate to Google Using Oauth2
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// </summary>
/// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
/// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>SheetsService used to make requests against the Sheets API</returns>
public static GmailService AuthenticateOauth(string clientId, string clientSecret, string userName)
{
try
{
if (string.IsNullOrEmpty(clientId))
throw new ArgumentNullException("clientId");
if (string.IsNullOrEmpty(clientSecret))
throw new ArgumentNullException("clientSecret");
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
string[] scopes = new string[] { GmailService.Scope.GmailSettingsSharing, //Manage your sensitive mail settings, including who can manage your mail
GmailService.Scope.GmailSettingsBasic, //Manage your basic mail settings
GmailService.Scope.GmailMetadata, //View your email message metadata such as labels and headers, but not the email body
GmailService.Scope.GmailReadonly, //View your emails messages and settings
GmailService.Scope.GmailCompose, //Manage drafts and send emails
GmailService.Scope.GmailInsert, //Insert mail into your mailbox
GmailService.Scope.GmailLabels, //Manage mailbox labels
GmailService.Scope.GmailModify, //View and modify but not delete your email
GmailService.Scope.GmailSend, //Send email on your behalf
GmailService.Scope.Https://MailGoogleCom/}; //View and manage your mail
var credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = System.IO.Path.Combine(credPath, ".credentials/apiName");
// Requesting Authentication or loading previously stored authentication for userName
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore(credPath, true)).Result;
// Returning the SheetsService
return new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Gmail Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
Console.WriteLine("Create Oauth2 account GmailService failed" + ex.Message);
throw new Exception("CreateServiceAccountGmailFailed", ex);
}
}
}
}