|
| 1 | +using System.Net.Mime; |
| 2 | +using Microsoft.AspNetCore.Mvc; |
| 3 | +using Microsoft.Extensions.Configuration; |
| 4 | +using CSharpApp.Models; |
| 5 | +using System.Net.Http; |
| 6 | +using System.Net.Http.Headers; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Newtonsoft.Json; |
| 9 | +using System.Collections.Generic; |
| 10 | +using Microsoft.AspNetCore.WebUtilities; |
| 11 | +using System; |
| 12 | +using System.Text; |
| 13 | +using System.Xml; |
| 14 | + |
| 15 | +namespace CSharpApp.Controllers |
| 16 | +{ |
| 17 | + public class HomeController : Controller |
| 18 | + { |
| 19 | + private readonly IConfiguration _configuration; |
| 20 | + private static JDeere _settings = new JDeere(); |
| 21 | + public HomeController(IConfiguration configuration) |
| 22 | + { |
| 23 | + _configuration = configuration; |
| 24 | + } |
| 25 | + |
| 26 | + public IActionResult Index() |
| 27 | + { |
| 28 | + _settings.ClientId = _configuration["JDeere:ClientId"]; |
| 29 | + _settings.ClientSecret = _configuration["JDeere:ClientSecret"]; |
| 30 | + _settings.WellKnown = _configuration["JDeere:WellKnown"]; |
| 31 | + _settings.ServerUrl = _configuration["JDeere:ServerUrl"]; |
| 32 | + _settings.CallbackUrl = _settings.ServerUrl + _configuration["JDeere:Callback"]; |
| 33 | + _settings.Scopes = _configuration["JDeere:Scopes"]; |
| 34 | + _settings.State = _configuration["JDeere:State"]; |
| 35 | + _settings.APIURL = _configuration["JDeere:ApiUrl"]; |
| 36 | + |
| 37 | + ViewBag.Settings = _settings; |
| 38 | + |
| 39 | + return View(); |
| 40 | + } |
| 41 | + |
| 42 | + [HttpPost] |
| 43 | + public async Task<IActionResult> Index(string ClientId, string ClientSecret, string WellKnown, string CallbackUrl, string Scopes, string State) |
| 44 | + { |
| 45 | + _settings.ClientId = ClientId; |
| 46 | + _settings.ClientSecret = ClientSecret; |
| 47 | + _settings.WellKnown = WellKnown; |
| 48 | + _settings.CallbackUrl = CallbackUrl; |
| 49 | + _settings.Scopes = Scopes; |
| 50 | + _settings.State = State; |
| 51 | + |
| 52 | + ViewBag.State = State; |
| 53 | + Dictionary<string, object> oAuthMetadata = await GetOAuthMetadata(WellKnown); |
| 54 | + string authEndpoint = oAuthMetadata["authorization_endpoint"].ToString(); |
| 55 | + |
| 56 | + var queryParameters = new Dictionary<string, string>(); |
| 57 | + queryParameters.Add("response_type", "code"); |
| 58 | + queryParameters.Add("scope", Scopes); |
| 59 | + queryParameters.Add("client_id", ClientId); |
| 60 | + queryParameters.Add("state", State); |
| 61 | + queryParameters.Add("redirect_uri", CallbackUrl); |
| 62 | + |
| 63 | + string redirectUrl = QueryHelpers.AddQueryString(authEndpoint, queryParameters); |
| 64 | + |
| 65 | + return Redirect(redirectUrl); |
| 66 | + } |
| 67 | + |
| 68 | + [Route("/callback")] |
| 69 | + public async Task<IActionResult> Callback(string code, string state) |
| 70 | + { |
| 71 | + Dictionary<string, object> oAuthMetadata = await GetOAuthMetadata(_settings.WellKnown); |
| 72 | + string tokenEndpoint = oAuthMetadata["token_endpoint"].ToString(); |
| 73 | + |
| 74 | + var queryParameters = new Dictionary<string, string>(); |
| 75 | + queryParameters.Add("grant_type", "authorization_code"); |
| 76 | + queryParameters.Add("code", code); |
| 77 | + queryParameters.Add("redirect_uri", _settings.CallbackUrl); |
| 78 | + |
| 79 | + HttpClient client = new HttpClient(); |
| 80 | + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); |
| 81 | + client.DefaultRequestHeaders.Add("authorization", $"Basic {GetBase64EncodedClientCredentials()}"); |
| 82 | + |
| 83 | + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, tokenEndpoint) |
| 84 | + { |
| 85 | + Content = new FormUrlEncodedContent(queryParameters) |
| 86 | + }; |
| 87 | + |
| 88 | + HttpResponseMessage response = await client.SendAsync(request); |
| 89 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 90 | + _settings.AccessToken = JsonConvert.DeserializeObject<Token>(responseContent); |
| 91 | + |
| 92 | + string organizationAccessUrl = await NeedsOrganizationAccess(); |
| 93 | + if (organizationAccessUrl != null) |
| 94 | + { |
| 95 | + return Redirect(organizationAccessUrl); |
| 96 | + } |
| 97 | + |
| 98 | + ViewBag.Settings = _settings; |
| 99 | + |
| 100 | + return View("Index"); |
| 101 | + } |
| 102 | + |
| 103 | + [HttpPost] |
| 104 | + [Route("/call-api")] |
| 105 | + public async Task<IActionResult> CallAPI(string url) |
| 106 | + { |
| 107 | + |
| 108 | + var response = await SecuredApiGetRequest(url); |
| 109 | + |
| 110 | + |
| 111 | + response.EnsureSuccessStatusCode(); |
| 112 | + |
| 113 | + var responseBody = await response.Content.ReadAsStringAsync(); |
| 114 | + ViewBag.APIResponse = responseBody; |
| 115 | + ViewBag.Settings = _settings; |
| 116 | + |
| 117 | + return View("Index"); |
| 118 | + } |
| 119 | + |
| 120 | + [Route("/refresh-access-token")] |
| 121 | + public async Task<IActionResult> RefreshAccessToken() |
| 122 | + { |
| 123 | + Dictionary<string, object> oAuthMetadata = await GetOAuthMetadata(_settings.WellKnown); |
| 124 | + string tokenEndpoint = oAuthMetadata["token_endpoint"].ToString(); |
| 125 | + |
| 126 | + var queryParameters = new Dictionary<string, string>(); |
| 127 | + queryParameters.Add("grant_type", "refresh_token"); |
| 128 | + queryParameters.Add("refresh_token", _settings.AccessToken.refresh_token); |
| 129 | + queryParameters.Add("redirect_uri", _settings.CallbackUrl); |
| 130 | + |
| 131 | + HttpClient client = new HttpClient(); |
| 132 | + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); |
| 133 | + client.DefaultRequestHeaders.Add("authorization", $"Basic {GetBase64EncodedClientCredentials()}"); |
| 134 | + |
| 135 | + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, tokenEndpoint) |
| 136 | + { |
| 137 | + Content = new FormUrlEncodedContent(queryParameters) |
| 138 | + }; |
| 139 | + |
| 140 | + HttpResponseMessage response = await client.SendAsync(request); |
| 141 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 142 | + _settings.AccessToken = JsonConvert.DeserializeObject<Token>(responseContent); |
| 143 | + |
| 144 | + ViewBag.Settings = _settings; |
| 145 | + |
| 146 | + return View("Index"); |
| 147 | + } |
| 148 | + |
| 149 | + private string GetBase64EncodedClientCredentials() |
| 150 | + { |
| 151 | + byte[] credentialBytes = Encoding.UTF8.GetBytes($"{_settings.ClientId}:{_settings.ClientSecret}"); |
| 152 | + return Convert.ToBase64String(credentialBytes); |
| 153 | + } |
| 154 | + |
| 155 | + private static async Task<Dictionary<string, object>> GetOAuthMetadata(string WellKnown) |
| 156 | + { |
| 157 | + HttpClient client = new HttpClient(); |
| 158 | + var response = await client.GetAsync(WellKnown); |
| 159 | + |
| 160 | + response.EnsureSuccessStatusCode(); |
| 161 | + |
| 162 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 163 | + var oAuthMetadata = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseContent); |
| 164 | + return oAuthMetadata; |
| 165 | + } |
| 166 | + |
| 167 | + private async Task<HttpResponseMessage> SecuredApiGetRequest(string url) |
| 168 | + { |
| 169 | + var client = new HttpClient(); |
| 170 | + var token = _settings.AccessToken.access_token; |
| 171 | + |
| 172 | + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); |
| 173 | + client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); |
| 174 | + |
| 175 | + |
| 176 | + |
| 177 | + return await client.GetAsync(url); |
| 178 | + } |
| 179 | + |
| 180 | + /// <summary>Check to see if the 'connections' rel is present for any organization. |
| 181 | + /// If the rel is present it means the oauth application has not completed it's |
| 182 | + /// access to an organization and must redirect the user to the uri provided |
| 183 | + /// in the link.</summary> |
| 184 | + /// <returns>A redirect uri if the <code>connections</code> |
| 185 | + /// connections rel is present or <null> if no redirect iszz |
| 186 | + /// required to finish the setup.</returns> |
| 187 | + private async Task<string> NeedsOrganizationAccess() |
| 188 | + { |
| 189 | + var response = await SecuredApiGetRequest(_settings.APIURL + "/1"); |
| 190 | + |
| 191 | + response.EnsureSuccessStatusCode(); |
| 192 | + var responseContent = await response.Content.ReadAsStringAsync(); |
| 193 | + |
| 194 | + XmlDocument doc = new XmlDocument(); |
| 195 | + |
| 196 | + doc.LoadXml(responseContent); |
| 197 | + |
| 198 | + XmlNodeList data = doc.GetElementsByTagName("Links"); |
| 199 | + |
| 200 | + for (int i = 0; i < data.Count; i++) |
| 201 | + { |
| 202 | + |
| 203 | + if (data[i].InnerText.StartsWith("connections")) |
| 204 | + { |
| 205 | + string connectionsLink = data[i].LastChild.LastChild.Value; |
| 206 | + |
| 207 | + return QueryHelpers.AddQueryString(connectionsLink, "redirect_uri", _settings.ServerUrl); |
| 208 | + } |
| 209 | + |
| 210 | + } |
| 211 | + return null; |
| 212 | + } |
| 213 | + } |
| 214 | +} |
| 215 | + |
0 commit comments