|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Net.Http; |
| 5 | +using System.Net.Http.Headers; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Microsoft.AspNetCore.Authentication; |
| 8 | +using Microsoft.AspNetCore.Authentication.OpenIdConnect; |
| 9 | +using Microsoft.AspNetCore.Authorization; |
| 10 | +using Microsoft.AspNetCore.Mvc; |
| 11 | +using Microsoft.IdentityModel.Clients.ActiveDirectory; |
| 12 | +using Newtonsoft.Json; |
| 13 | +using TodoListWebApp.Models; |
| 14 | + |
| 15 | +// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 |
| 16 | + |
| 17 | +namespace TodoListWebApp.Controllers |
| 18 | +{ |
| 19 | + [Authorize] |
| 20 | + public class TodoController : Controller |
| 21 | + { |
| 22 | + // GET: /<controller>/ |
| 23 | + public async Task<IActionResult> Index() |
| 24 | + { |
| 25 | + AuthenticationResult result = null; |
| 26 | + List<TodoItem> itemList = new List<TodoItem>(); |
| 27 | + |
| 28 | + try |
| 29 | + { |
| 30 | + // Because we signed-in already in the WebApp, the userObjectId is know |
| 31 | + string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; |
| 32 | + |
| 33 | + // Using ADAL.Net, get a bearer token to access the TodoListService |
| 34 | + AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session)); |
| 35 | + ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret); |
| 36 | + result = await authContext.AcquireTokenSilentAsync(AzureAdOptions.Settings.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); |
| 37 | + |
| 38 | + // Retrieve the user's To Do List. |
| 39 | + HttpClient client = new HttpClient(); |
| 40 | + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, AzureAdOptions.Settings.TodoListBaseAddress + "/api/todolist"); |
| 41 | + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); |
| 42 | + HttpResponseMessage response = await client.SendAsync(request); |
| 43 | + |
| 44 | + // Return the To Do List in the view. |
| 45 | + if (response.IsSuccessStatusCode) |
| 46 | + { |
| 47 | + List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>(); |
| 48 | + JsonSerializerSettings settings = new JsonSerializerSettings(); |
| 49 | + String responseString = await response.Content.ReadAsStringAsync(); |
| 50 | + responseElements = JsonConvert.DeserializeObject<List<Dictionary<String, String>>>(responseString, settings); |
| 51 | + foreach (Dictionary<String, String> responseElement in responseElements) |
| 52 | + { |
| 53 | + TodoItem newItem = new TodoItem(); |
| 54 | + newItem.Title = responseElement["title"]; |
| 55 | + newItem.Owner = responseElement["owner"]; |
| 56 | + itemList.Add(newItem); |
| 57 | + } |
| 58 | + |
| 59 | + return View(itemList); |
| 60 | + } |
| 61 | + else |
| 62 | + { |
| 63 | + // |
| 64 | + // If the call failed with access denied, then drop the current access token from the cache, |
| 65 | + // and show the user an error indicating they might need to sign-in again. |
| 66 | + // |
| 67 | + if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) |
| 68 | + { |
| 69 | + var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == AzureAdOptions.Settings.TodoListResourceId); |
| 70 | + foreach (TokenCacheItem tci in todoTokens) |
| 71 | + authContext.TokenCache.DeleteItem(tci); |
| 72 | + |
| 73 | + ViewBag.ErrorMessage = "UnexpectedError"; |
| 74 | + TodoItem newItem = new TodoItem(); |
| 75 | + newItem.Title = "(No items in list)"; |
| 76 | + itemList.Add(newItem); |
| 77 | + return View(itemList); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + catch (Exception ee) |
| 82 | + { |
| 83 | + if (HttpContext.Request.Query["reauth"] == "True") |
| 84 | + { |
| 85 | + // |
| 86 | + // Send an OpenID Connect sign-in request to get a new set of tokens. |
| 87 | + // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. |
| 88 | + // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. |
| 89 | + // |
| 90 | + return new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme); |
| 91 | + } |
| 92 | + // |
| 93 | + // The user needs to re-authorize. Show them a message to that effect. |
| 94 | + // |
| 95 | + TodoItem newItem = new TodoItem(); |
| 96 | + newItem.Title = "(Sign-in required to view to do list.)"; |
| 97 | + itemList.Add(newItem); |
| 98 | + ViewBag.ErrorMessage = "AuthorizationRequired"; |
| 99 | + return View(itemList); |
| 100 | + } |
| 101 | + // |
| 102 | + // If the call failed for any other reason, show the user an error. |
| 103 | + // |
| 104 | + return View("Error"); |
| 105 | + } |
| 106 | + |
| 107 | + |
| 108 | + |
| 109 | + [HttpPost] |
| 110 | + public async Task<ActionResult> Index(string item) |
| 111 | + { |
| 112 | + if (ModelState.IsValid) |
| 113 | + { |
| 114 | + // |
| 115 | + // Retrieve the user's tenantID and access token since they are parameters used to call the To Do service. |
| 116 | + // |
| 117 | + AuthenticationResult result = null; |
| 118 | + List<TodoItem> itemList = new List<TodoItem>(); |
| 119 | + |
| 120 | + try |
| 121 | + { |
| 122 | + string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; |
| 123 | + AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session)); |
| 124 | + ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret); |
| 125 | + result = await authContext.AcquireTokenSilentAsync(AzureAdOptions.Settings.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); |
| 126 | + |
| 127 | + // Forms encode todo item, to POST to the todo list web api. |
| 128 | + HttpContent content = new StringContent(JsonConvert.SerializeObject(new { Title = item }), System.Text.Encoding.UTF8, "application/json"); |
| 129 | + |
| 130 | + // |
| 131 | + // Add the item to user's To Do List. |
| 132 | + // |
| 133 | + HttpClient client = new HttpClient(); |
| 134 | + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, AzureAdOptions.Settings.TodoListBaseAddress + "/api/todolist"); |
| 135 | + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); |
| 136 | + request.Content = content; |
| 137 | + HttpResponseMessage response = await client.SendAsync(request); |
| 138 | + |
| 139 | + // |
| 140 | + // Return the To Do List in the view. |
| 141 | + // |
| 142 | + if (response.IsSuccessStatusCode) |
| 143 | + { |
| 144 | + return RedirectToAction("Index"); |
| 145 | + } |
| 146 | + else |
| 147 | + { |
| 148 | + // |
| 149 | + // If the call failed with access denied, then drop the current access token from the cache, |
| 150 | + // and show the user an error indicating they might need to sign-in again. |
| 151 | + // |
| 152 | + if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) |
| 153 | + { |
| 154 | + var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == AzureAdOptions.Settings.TodoListResourceId); |
| 155 | + foreach (TokenCacheItem tci in todoTokens) |
| 156 | + authContext.TokenCache.DeleteItem(tci); |
| 157 | + |
| 158 | + ViewBag.ErrorMessage = "UnexpectedError"; |
| 159 | + TodoItem newItem = new TodoItem(); |
| 160 | + newItem.Title = "(No items in list)"; |
| 161 | + itemList.Add(newItem); |
| 162 | + return View(newItem); |
| 163 | + } |
| 164 | + } |
| 165 | + } |
| 166 | + catch (Exception ee) |
| 167 | + { |
| 168 | + // |
| 169 | + // The user needs to re-authorize. Show them a message to that effect. |
| 170 | + // |
| 171 | + TodoItem newItem = new TodoItem(); |
| 172 | + newItem.Title = "(No items in list)"; |
| 173 | + itemList.Add(newItem); |
| 174 | + ViewBag.ErrorMessage = "AuthorizationRequired"; |
| 175 | + return View(itemList); |
| 176 | + } |
| 177 | + // |
| 178 | + // If the call failed for any other reason, show the user an error. |
| 179 | + // |
| 180 | + return View("Error"); |
| 181 | + } |
| 182 | + return View("Error"); |
| 183 | + } |
| 184 | + } |
| 185 | +} |
0 commit comments