-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
296 lines (255 loc) · 11.4 KB
/
MainWindow.xaml.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
The MIT License (MIT)
Copyright (c) 2015 Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Configuration;
// The following using statements were added for this sample.
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Web.Script.Serialization;
using System.Windows;
namespace TodoListClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//
// The Client ID is used by the application to uniquely identify itself to Azure AD.
// The Tenant is the name of the Azure AD tenant in which this application is registered.
// The AAD Instance is the instance of Azure, for example public Azure or Azure China.
// The Redirect URI is the URI where Azure AD will return OAuth responses.
// The Authority is the sign-in URL of the tenant.
//
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
Uri redirectUri = new Uri(ConfigurationManager.AppSettings["ida:RedirectUri"]);
private static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
//
// To authenticate to the To Do list service, the client needs to know the service's App ID URI.
// To contact the To Do list service we need it's URL as well.
//
private static string todoListResourceId = ConfigurationManager.AppSettings["todo:TodoListResourceId"];
private static string todoListBaseAddress = ConfigurationManager.AppSettings["todo:TodoListBaseAddress"];
private HttpClient httpClient = new HttpClient();
private AuthenticationContext authContext = null;
// Button strings
const string signInString = "Sign In";
const string clearCacheString = "Clear Cache";
public MainWindow()
{
InitializeComponent();
authContext = new AuthenticationContext(authority, new FileCache());
GetTodoList();
}
private void GetTodoList()
{
GetTodoList(SignInButton.Content.ToString() != clearCacheString);
}
private async void GetTodoList(bool isAppStarting)
{
//
// Get an access token to call the To Do service.
//
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenSilentAsync(todoListResourceId, clientId);
SignInButton.Content = clearCacheString;
this.SetUserName(result.UserInfo);
}
catch (AdalException ex)
{
// There is no access token in the cache, so prompt the user to sign-in.
if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
{
if (!isAppStarting)
{
MessageBox.Show("Please sign in to view your To-Do list");
SignInButton.Content = signInString;
}
}
else
{
// An unexpected error occurred.
string message = ex.Message;
if (ex.InnerException != null)
{
message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
}
MessageBox.Show(message);
}
UserName.Content = Properties.Resources.UserNotSignedIn;
return;
}
// Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do list service.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// Call the To Do list service.
HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "/api/todolist");
if (response.IsSuccessStatusCode)
{
// Read the response and databind to the GridView to display To Do items.
string s = await response.Content.ReadAsStringAsync();
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<TodoItem> toDoArray = serializer.Deserialize<List<TodoItem>>(s);
TodoList.ItemsSource = toDoArray.Select(t => new { t.Title });
}
else
{
MessageBox.Show("An error occurred : " + response.ReasonPhrase);
}
return;
}
private async void AddTodoItem(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(TodoText.Text))
{
MessageBox.Show("Please enter a value for the To Do item name");
return;
}
//
// Get an access token to call the To Do service.
//
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenSilentAsync(todoListResourceId, clientId);
this.SetUserName(result.UserInfo);
}
catch (AdalException ex)
{
// There is no access token in the cache, so prompt the user to sign-in.
if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
{
MessageBox.Show("Please sign in first");
SignInButton.Content = signInString;
}
else
{
// An unexpected error occurred.
string message = ex.Message;
if (ex.InnerException != null)
{
message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
}
MessageBox.Show(message);
}
UserName.Content = Properties.Resources.UserNotSignedIn;
return;
}
//
// Call the To Do service.
//
// Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do service.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// Forms encode Todo item, to POST to the todo list web api.
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("Title", TodoText.Text) });
// Call the To Do list service.
HttpResponseMessage response = await httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content);
if (response.IsSuccessStatusCode)
{
TodoText.Text = "";
GetTodoList();
}
else
{
MessageBox.Show("An error occurred : " + response.ReasonPhrase);
}
}
private async void SignIn(object sender = null, RoutedEventArgs args = null)
{
// If there is already a token in the cache, clear the cache and update the label on the button.
if (SignInButton.Content.ToString() == clearCacheString)
{
TodoList.ItemsSource = string.Empty;
authContext.TokenCache.Clear();
// Also clear cookies from the browser control.
SignInButton.Content = signInString;
UserName.Content = Properties.Resources.UserNotSignedIn;
return;
}
//
// Get an access token to call the To Do list service.
//
AuthenticationResult result = null;
try
{
// Force a sign-in (PromptBehavior.Always), as the ADAL web browser might contain cookies for the current user, and using .Auto
// would re-sign-in the same user
result = await authContext.AcquireTokenAsync(todoListResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Always));
SignInButton.Content = clearCacheString;
SetUserName(result.UserInfo);
GetTodoList();
}
catch (AdalException ex)
{
if (ex.ErrorCode == "access_denied")
{
// The user canceled sign in, take no action.
}
else
{
// An unexpected error occurred.
string message = ex.Message;
if (ex.InnerException != null)
{
message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
}
MessageBox.Show(message);
}
UserName.Content = Properties.Resources.UserNotSignedIn;
return;
}
}
// Set user name to text box
private void SetUserName(UserInfo userInfo)
{
string userName = null;
if (userInfo != null)
{
if (userInfo.GivenName != null && userInfo.FamilyName != null)
{
userName = userInfo.GivenName + " " + userInfo.FamilyName;
}
else if (userInfo.FamilyName != null)
{
userName = userInfo.FamilyName;
}
else if (userInfo.GivenName != null)
{
userName = userInfo.GivenName;
}
else if (userInfo.UniqueId != null)
{
userName = userInfo.UniqueId;
}
}
if (userName == null)
userName = Properties.Resources.UserNotIdentified;
UserName.Content = userName;
}
}
}