· 6 years ago · Dec 29, 2018, 04:52 PM
1UserCredential credential;
2 credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
3 new Uri("ms-appx:///Assets/client_secrets.json"),
4 Scopes,
5 "user",
6 CancellationToken.None).Result;
7
8
9 // Create Google Calendar API service.
10 var service = new CalendarService(new BaseClientService.Initializer()
11 {
12 HttpClientInitializer = credential,
13 ApplicationName = ApplicationName,
14 });
15
16 var calendarService = new CalendarService(new BaseClientService.Initializer
17 {
18 HttpClientInitializer = credential,
19 ApplicationName = "Windows 10 Calendar sample"
20 });
21 var calendarListResource = await calendarService.CalendarList.List().ExecuteAsync();
22
23var clientId = "{Your Client Id}";
24var redirectURI = "pw.oauth2:/oauth2redirect";
25var scope = "https://www.googleapis.com/auth/calendar.readonly";
26var SpotifyUrl = $"https://accounts.google.com/o/oauth2/auth?client_id={clientId}&redirect_uri={Uri.EscapeDataString(redirectURI)}&response_type=code&scope={Uri.EscapeDataString(scope)}";
27var StartUri = new Uri(SpotifyUrl);
28var EndUri = new Uri(redirectURI);
29
30// Get Authorization code
31WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
32if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
33{
34 var decoder = new WwwFormUrlDecoder(new Uri(WebAuthenticationResult.ResponseData).Query);
35 if (decoder[0].Name != "code")
36 {
37 System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {decoder.GetFirstValueByName("error")}.");
38 return;
39 }
40
41 var autorizationCode = decoder.GetFirstValueByName("code");
42
43
44 //Get Access Token
45 var pairs = new Dictionary<string, string>();
46 pairs.Add("code", autorizationCode);
47 pairs.Add("client_id", clientId);
48 pairs.Add("redirect_uri", redirectURI);
49 pairs.Add("grant_type", "authorization_code");
50
51 var formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);
52
53 var client = new Windows.Web.Http.HttpClient();
54 var httpResponseMessage = await client.PostAsync(new Uri("https://www.googleapis.com/oauth2/v4/token"), formContent);
55 if (!httpResponseMessage.IsSuccessStatusCode)
56 {
57 System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {httpResponseMessage.StatusCode}.");
58 return;
59 }
60
61 string jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
62 var jsonObject = Windows.Data.Json.JsonObject.Parse(jsonString);
63 var accessToken = jsonObject["access_token"].GetString();
64
65
66 //Call Google Calendar API
67 using (var httpRequest = new Windows.Web.Http.HttpRequestMessage())
68 {
69 string calendarAPI = "https://www.googleapis.com/calendar/v3/users/me/calendarList";
70
71 httpRequest.Method = Windows.Web.Http.HttpMethod.Get;
72 httpRequest.RequestUri = new Uri(calendarAPI);
73 httpRequest.Headers.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", accessToken);
74
75 var response = await client.SendRequestAsync(httpRequest);
76
77 if (response.IsSuccessStatusCode)
78 {
79 var listString = await response.Content.ReadAsStringAsync();
80 //TODO
81 }
82 }
83}
84
85namespace GoogleProxy
86{
87public class GoogleService
88{
89 public CalendarService calendarService { get; private set; }
90
91 public DriveService driveService { get; private set; }
92
93
94 public GoogleService()
95 {
96
97 }
98
99 public void Initialize(AuthResult authResult)
100 {
101 var credential = GetCredentialForApi(authResult);
102 var baseInitializer = new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "{your app name here}" };
103
104 calendarService = new Google.Apis.Calendar.v3.CalendarService(baseInitializer);
105 driveService = new Google.Apis.Drive.v3.DriveService(baseInitializer);
106 }
107
108 private UserCredential GetCredentialForApi(AuthResult authResult)
109 {
110 var initializer = new GoogleAuthorizationCodeFlow.Initializer
111 {
112 ClientSecrets = new ClientSecrets
113 {
114 ClientId = "{your app client id here}",
115 ClientSecret = "",
116 },
117 Scopes = new string[] { "openid", "email", "profile", "https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/calendar.events.readonly", "https://www.googleapis.com/auth/drive.readonly" },
118 };
119
120 var flow = new GoogleAuthorizationCodeFlow(initializer);
121
122 var token = new TokenResponse()
123 {
124 AccessToken = authResult.AccessToken,
125 RefreshToken = authResult.RefreshToken,
126 ExpiresInSeconds = authResult.ExpirationInSeconds,
127 IdToken = authResult.IdToken,
128 IssuedUtc = authResult.IssueDateTime,
129 Scope = "openid email profile https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/drive.readonly",
130 TokenType = "bearer" };
131
132 return new UserCredential(flow, authResult.Id, token);
133 }
134
135}
136}
137
138protected override void OnActivated(IActivatedEventArgs args)
139 {
140 base.OnActivated(args);
141 if (args.Kind == ActivationKind.Protocol)
142 {
143 ProtocolActivatedEventArgs protocolArgs = (ProtocolActivatedEventArgs)args;
144 Uri uri = protocolArgs.Uri;
145 Debug.WriteLine("Authorization Response: " + uri.AbsoluteUri);
146 locator.AccountsService.GoogleExternalAuthWait.Set(uri.Query);
147 }
148 }
149
150public class AsyncManualResetEvent<T>
151{
152 private volatile TaskCompletionSource<T> m_tcs = new TaskCompletionSource<T>();
153
154 public Task<T> WaitAsync() { return m_tcs.Task; }
155
156 public void Set(T TResult) { m_tcs.TrySetResult(TResult); }
157
158 public bool IsReset => !m_tcs.Task.IsCompleted;
159
160 public void Reset()
161 {
162 while (true)
163 {
164 var tcs = m_tcs;
165 if (!tcs.Task.IsCompleted ||
166 Interlocked.CompareExchange(ref m_tcs, new TaskCompletionSource<T>(), tcs) == tcs)
167 return;
168 }
169 }
170}
171
172private async Task<AuthResult> AuthenticateGoogleAsync()
173 {
174 try
175 {
176 var stateGuid = Guid.NewGuid().ToString();
177 var expiration = DateTimeOffset.Now;
178 var url = $"{GoogleAuthorizationEndpoint}?client_id={WebUtility.UrlEncode(GoogleAccountClientId)}&redirect_uri={WebUtility.UrlEncode(GoogleRedirectURI)}&state={stateGuid}&scope={WebUtility.UrlEncode(GoogleScopes)}&display=popup&response_type=code";
179
180 var success = Windows.System.Launcher.LaunchUriAsync(new Uri(url));
181
182 GoogleExternalAuthWait = new AsyncManualResetEvent<string>();
183
184 var query = await GoogleExternalAuthWait.WaitAsync();
185
186 var dictionary = query.Substring(1).Split('&').ToDictionary(x => x.Split('=')[0], x => Uri.UnescapeDataString(x.Split('=')[1]));
187 if (dictionary.ContainsKey("error"))
188 {
189 return null;
190 }
191 if (!dictionary.ContainsKey("code") || !dictionary.ContainsKey("state"))
192 {
193 return null;
194 }
195 if (dictionary["state"] != stateGuid)
196 return null;
197
198 string tokenRequestBody = $"code={dictionary["code"]}&redirect_uri={Uri.EscapeDataString(GoogleRedirectURI)}&client_id={GoogleAccountClientId}&access_type=offline&scope=&grant_type=authorization_code";
199
200 StringContent content = new StringContent(tokenRequestBody, Encoding.UTF8, "application/x-www-form-urlencoded");
201
202
203 // Performs the authorization code exchange.
204 using (HttpClientHandler handler = new HttpClientHandler())
205 {
206 handler.AllowAutoRedirect = true;
207 using (HttpClient client = new HttpClient(handler))
208 {
209 HttpResponseMessage response = await client.PostAsync(GoogleTokenEndpoint, content);
210 if (response.IsSuccessStatusCode)
211 {
212
213 var stringResponse = await response.Content.ReadAsStringAsync();
214 var json = JObject.Parse(stringResponse);
215 var id = DecodeIdFromJWT((string)json["id_token"]);
216 var oauthToken = new AuthResult()
217 {
218 Provider = AccountType.Google,
219 AccessToken = (string)json["access_token"],
220 Expiration = DateTimeOffset.Now + TimeSpan.FromSeconds(int.Parse((string)json["expires_in"])),
221 Id = id,
222 IdToken = (string)json["id_token"],
223 ExpirationInSeconds = long.Parse((string)json["expires_in"]),
224 IssueDateTime = DateTime.Now,
225 RefreshToken = (string)json["refresh_token"]
226 };
227 return oauthToken;
228 }
229 else
230 {
231 return null;
232 }
233
234 }
235 }
236 }
237 catch (Exception ex)
238 {
239 Debug.WriteLine(ex.Message);
240 return null;
241 }
242 }