This repository has been archived by the owner on Jan 29, 2020. It is now read-only.
/
Program.cs
304 lines (280 loc) · 12.2 KB
/
Program.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
297
298
299
300
301
302
303
304
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Globalization;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace TodoListClient
{
class Program
{
#region Init
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
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 its URL as well.
//
private static string todoListResourceId = ConfigurationManager.AppSettings["todo:TodoListResourceId"];
private static string todoListBaseAddress = ConfigurationManager.AppSettings["todo:TodoListBaseAddress"];
private static AuthenticationContext authContext = null;
#endregion
static void Main(string[] args)
{
string commandString = string.Empty;
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("**************************************************");
Console.WriteLine("* ToDo List Text Client *");
Console.WriteLine("* *");
Console.WriteLine("* Type commands to manage your ToDos *");
Console.WriteLine("* *");
Console.WriteLine("**************************************************");
Console.WriteLine("");
// Initialize the AuthenticationContext for the AAD tenant of choice.
// Add a persistent file-based token cache.
authContext = new AuthenticationContext(authority, new FileCache());
// main command cycle
while (!commandString.Equals("Exit", StringComparison.InvariantCultureIgnoreCase))
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Enter command (list | add | clear | exit | help) >");
commandString = Console.ReadLine();
switch(commandString.ToUpper())
{
case "LIST": ListTodo();
break;
case "ADD": AddTodo();
break;
case "CLEAR": ClearCache();
break;
case "HELP": Help();
break;
case "EXIT": Console.WriteLine("Bye!"); ;
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid command.");
break;
}
}
}
#region Textual UX
// Gather user credentials form the command line
static UserCredential TextualPrompt()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("There is no token in the cache or you are not connected to your domain.");
Console.WriteLine("Please enter username and password to sign in.");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("User>");
string user = Console.ReadLine();
Console.WriteLine("Password>");
string password = ReadPasswordFromConsole();
Console.WriteLine("");
return new UserPasswordCredential(user, password);
}
// Display exceptions text on the console
static void ShowError(Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("An unexpected error occurred.");
string message = ex.Message;
if (ex.InnerException != null)
{
message += Environment.NewLine + "Inner Exception : " + ex.InnerException.Message;
}
Console.WriteLine("Message: {0}",message);
}
// Obscure the password being entered
static string ReadPasswordFromConsole()
{
string password = string.Empty;
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
password += key.KeyChar;
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && password.Length > 0)
{
password = password.Substring(0, (password.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
return password;
}
#endregion
#region Commands
// List all the ToDos for the current user.
// If there is no valid token available, obtain a new one.
static void ListTodo()
{
#region Obtain token
AuthenticationResult result = null;
// first, try to get a token silently
try
{
result = authContext.AcquireTokenSilentAsync(todoListResourceId, clientId).Result;
}
catch (AggregateException exc)
{
AdalException ex = exc.InnerException as AdalException;
// There is no token in the cache; prompt the user to sign-in.
if (ex != null && ex.ErrorCode != "failed_to_acquire_token_silently")
{
// An unexpected error occurred.
ShowError(ex);
return;
}
}
if (result == null)
{
UserCredential uc = TextualPrompt();
// if you want to use Windows integrated auth, comment the line above and uncomment the one below
// UserCredential uc = new UserCredential();
try
{
result = authContext.AcquireTokenAsync(todoListResourceId, clientId, uc).Result;
}
catch (Exception ee)
{
ShowError(ee);
return;
}
}
#endregion
#region Call Web API
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = httpClient.GetAsync(todoListBaseAddress + "/api/todolist").Result;
if (response.IsSuccessStatusCode)
{
string rezstring = response.Content.ReadAsStringAsync().Result;
var todoArray = JArray.Parse(rezstring);
Console.ForegroundColor = ConsoleColor.Green;
foreach (var todo in todoArray)
{
Console.WriteLine(todo["Title"]);
}
}
#endregion
#region Error handling
else
{
Console.ForegroundColor = ConsoleColor.Red;
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
// If the To Do list service returns access denied, clear the token cache and have the user sign-in again.
Console.WriteLine("Sorry, you don't have access to the To Do Service. You might need to sign up.");
authContext.TokenCache.Clear();
}
else
{
Console.WriteLine("Sorry, an error occurred accessing your To Do list. Please try again.");
}
}
#endregion
}
// Add a new ToDo in the list of the current user.
// If there is no valid token available, obtain a new one.
static void AddTodo()
{
#region Obtain token
AuthenticationResult result = null;
// first, try to get a token silently
try
{
result = authContext.AcquireTokenSilentAsync(todoListResourceId, clientId).Result;
}
catch (AggregateException exc)
{
AdalException ex = exc.InnerException as AdalException;
// There is no token in the cache; prompt the user to sign-in.
if (ex != null && ex.ErrorCode != "failed_to_acquire_token_silently")
{
// An unexpected error occurred.
ShowError(ex);
return;
}
}
if (result == null)
{
UserCredential uc = TextualPrompt();
// if you want to use Windows integrated auth, comment the line above and uncomment the one below
// UserCredential uc = new UserCredential();
try
{
result = authContext.AcquireTokenAsync(todoListResourceId, clientId, uc).Result;
}
catch (Exception ee)
{
ShowError(ee);
return;
}
}
#endregion
#region Call Web API
Console.WriteLine("Enter new todo description >");
string descr = Console.ReadLine();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("Title", descr) });
var response = httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content).Result;
if (response.IsSuccessStatusCode)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("New ToDo '{0}' successfully added.",descr);
}
#endregion
#region Error handling
else
{
Console.ForegroundColor = ConsoleColor.Red;
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
// If the To Do list service returns access denied, clear the token cache and have the user sign-in again.
Console.WriteLine("Sorry, you don't have access to the To Do Service. You might need to sign up.");
authContext.TokenCache.Clear();
}
else
{
Console.WriteLine("Sorry, an error occurred accessing your To Do list. Please try again.");
}
}
#endregion
}
// Empties the token cache
static void ClearCache()
{
authContext.TokenCache.Clear();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Token cache cleared.");
}
static void Help()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("LIST - lists all of your ToDo. Requires sign in");
Console.WriteLine("ADD - adds a new ToDo to your list. Requires sign in");
Console.WriteLine("CLEAR - empties the token cache, allowing you to sign in as a different user");
Console.WriteLine("HELP - displays this page");
Console.WriteLine("EXIT - closes this program");
Console.WriteLine("");
}
#endregion
}
}