/// <summary> /// Get the keycloak role that matches the PIMS claim. /// If it doesn't exist, create it in keycloak. /// </summary> /// <param name="claim"></param> /// <returns></returns> private async Task <KModel.RoleModel> GetKeycloakRoleAsync(ClaimModel claim) { try { // Make a request to keycloak to find a matching role. // If one is found, sync both keycloak and PIMS. // If one is not found, add it to keycloak and sync with PIMS. return(await _client.HandleRequestAsync <KModel.RoleModel>(HttpMethod.Get, $"{_options.Auth.Keycloak.Admin.Authority}/roles/{claim.Name}")); } catch (HttpClientRequestException ex) { if (ex.StatusCode == HttpStatusCode.NotFound) { var krole = new KModel.RoleModel() { Name = claim.Name, Description = claim.Description, Composite = false, ClientRole = false, ContainerId = _options.Auth.Keycloak.Realm }; // Add the role to keycloak and sync with PIMS. var kresponse = await _client.SendJsonAsync($"{_options.Auth.Keycloak.Admin.Authority}/roles", HttpMethod.Post, krole); if (kresponse.StatusCode == HttpStatusCode.Created) { return(await GetKeycloakRoleAsync(claim)); } else { throw new HttpClientRequestException(kresponse, $"Failed to add the role '{claim.Name}' to keycloak"); } } throw ex; } }
/// <summary> /// Update the realm information. /// </summary> /// <returns></returns> private async Task UpdateRealmAsync() { _logger.LogInformation($"Updating realm '{_options.Realm.Name}'"); // Determine if realm exists, it will throw an exception if it doesn't. var realm = await _client.HandleGetAsync <KModel.RealmModel>(_client.AdminRoute()); realm.DisplayName = _options.Realm.DisplayName; realm.DisplayNameHtml = _options.Realm.DisplayNameHtml; var rRes = await _client.SendJsonAsync(_client.AdminRoute(), HttpMethod.Put, realm); if (!rRes.IsSuccessStatusCode) { throw new HttpClientRequestException(rRes); } await AddUpdateRealmRolesAsync(); await AddUpdateGroupsAsync(); await AddUpdateClientsAsync(); }
/// <summary> /// Make an HTTP request to the configured endpoint URL. /// </summary> /// <param name="url"></param> /// <param name="items"></param> /// <param name="method"></param> /// <returns></returns> private async Task <HttpResponseMessage> SendAsync(HttpMethod method, string url, IEnumerable <object> items) { _logger.LogInformation($"Sending {items.Count()} items to {url}"); return(await _client.SendJsonAsync(url, method, items)); }