using IdentityModel.Client; using System; using System.Net.Http; using System.Threading.Tasks; public class KeycloakService { private readonly HttpClient _httpClient; private static readonly string KeycloakAuthUrl = "http://localhost:8080/realms/master/protocol/openid-connect/token"; private static readonly string ClientId = "GoodBooks"; private static readonly string ClientSecret = "cGZTwahvvm7EnuABvy1bTepzoFrP0Orx"; public KeycloakService() { _httpClient = new HttpClient(); } public async Task GetAccessTokenAsync(string username, string password) { try { var tokenRequest = new PasswordTokenRequest { Address = KeycloakAuthUrl, ClientId = ClientId, ClientSecret = ClientSecret, UserName = username, Password = password, Scope = "openid", GrantType = "password" }; var tokenResponse = await _httpClient.RequestPasswordTokenAsync(tokenRequest); if (tokenResponse.IsError) { throw new Exception($"Keycloak Authentication failed: {tokenResponse.Error}"); } return tokenResponse.AccessToken; } catch(Exception ex) { throw new Exception($"Keycloak Authentication failed: {ex.Message}"); } } }