|
| 1 | +// <copyright file="IResourceService.cs" company="PlaceholderCompany"> |
| 2 | +// Copyright (c) PlaceholderCompany. All rights reserved. |
| 3 | +// </copyright> |
| 4 | + |
| 5 | +namespace Cook; |
| 6 | + |
| 7 | +using System.Net.Http.Headers; |
| 8 | +using System.Text.Json; |
| 9 | +using System.Text.Json.Serialization; |
| 10 | + |
| 11 | +public interface IResourceService |
| 12 | +{ |
| 13 | + Task<string> GetContentAsync(string name); |
| 14 | +} |
| 15 | + |
| 16 | +public class ResourceService : IResourceService |
| 17 | +{ |
| 18 | + private readonly IConfiguration configuration; |
| 19 | + private readonly HttpClient httpClient; |
| 20 | + private OAuth2TokenResponse? cachedToken; |
| 21 | + |
| 22 | + public ResourceService(IConfiguration configuration, HttpClient httpClient) |
| 23 | + { |
| 24 | + this.configuration = configuration; |
| 25 | + this.httpClient = httpClient; |
| 26 | + } |
| 27 | + |
| 28 | + /// <inheritdoc/> |
| 29 | + public async Task<string> GetContentAsync(string name) |
| 30 | + { |
| 31 | + try |
| 32 | + { |
| 33 | + var configServerUri = this.configuration["spring:cloud:config:uri"]; |
| 34 | + |
| 35 | + var appName = this.configuration["spring:application:name"] ?? "application"; |
| 36 | + var profile = this.configuration["spring:cloud:config:env"] ?? "default"; |
| 37 | + var label = this.configuration["spring:cloud:config:label"] ?? "main"; |
| 38 | + |
| 39 | + var accessToken = await this.GetOrRefreshAccessTokenAsync(); |
| 40 | + |
| 41 | + var request = new HttpRequestMessage(HttpMethod.Get, $"{configServerUri}/{appName}/{profile}/{label}/{name}"); |
| 42 | + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); |
| 43 | + |
| 44 | + var response = await this.httpClient.SendAsync(request); |
| 45 | + if (response.IsSuccessStatusCode) |
| 46 | + { |
| 47 | + return await response.Content.ReadAsStringAsync(); |
| 48 | + } |
| 49 | + else |
| 50 | + { |
| 51 | + throw new HttpRequestException($"Failed to fetch resource: {response.StatusCode} - {response.ReasonPhrase}"); |
| 52 | + } |
| 53 | + } |
| 54 | + catch (Exception ex) |
| 55 | + { |
| 56 | + throw new InvalidOperationException($"Error fetching resource: {ex.Message}", ex); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + private async Task<string> GetOrRefreshAccessTokenAsync() |
| 61 | + { |
| 62 | + if (this.cachedToken != null && DateTime.UtcNow < this.cachedToken.ExpirationTime) |
| 63 | + { |
| 64 | + return this.cachedToken.AccessToken; |
| 65 | + } |
| 66 | + |
| 67 | + var clientId = this.configuration["spring:cloud:config:clientId"]; |
| 68 | + var clientSecret = this.configuration["spring:cloud:config:clientSecret"]; |
| 69 | + var accessTokenUri = this.configuration["spring:cloud:config:accessTokenUri"]; |
| 70 | + |
| 71 | + if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret) || string.IsNullOrEmpty(accessTokenUri)) |
| 72 | + { |
| 73 | + throw new InvalidOperationException("OAuth2 credentials not configured"); |
| 74 | + } |
| 75 | + |
| 76 | + var tokenRequest = new FormUrlEncodedContent(new[] |
| 77 | + { |
| 78 | + new KeyValuePair<string, string>("grant_type", "client_credentials"), |
| 79 | + new KeyValuePair<string, string>("client_id", clientId), |
| 80 | + new KeyValuePair<string, string>("client_secret", clientSecret), |
| 81 | + }); |
| 82 | + |
| 83 | + var tokenResponse = await this.httpClient.PostAsync(accessTokenUri, tokenRequest); |
| 84 | + if (!tokenResponse.IsSuccessStatusCode) |
| 85 | + { |
| 86 | + throw new HttpRequestException($"Failed to get access token: {tokenResponse.StatusCode} - {tokenResponse.ReasonPhrase}"); |
| 87 | + } |
| 88 | + |
| 89 | + this.cachedToken = this.ExtractTokenData(await tokenResponse.Content.ReadAsStringAsync()); |
| 90 | + |
| 91 | + return this.cachedToken.AccessToken; |
| 92 | + } |
| 93 | + |
| 94 | + private OAuth2TokenResponse ExtractTokenData(string tokenResponse) |
| 95 | + { |
| 96 | + return JsonSerializer.Deserialize<OAuth2TokenResponse>(tokenResponse) ?? new OAuth2TokenResponse(); |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +public class OAuth2TokenResponse |
| 101 | +{ |
| 102 | + [JsonPropertyName("access_token")] |
| 103 | + public string AccessToken { get; set; } = string.Empty; |
| 104 | + |
| 105 | + [JsonPropertyName("expires_in")] |
| 106 | + public int ExpiresIn { get; set; } = 3600; |
| 107 | + |
| 108 | + public DateTime ExpirationTime => DateTime.UtcNow.AddSeconds(this.ExpiresIn - 10); // Subtract 10 seconds for safety |
| 109 | +} |
0 commit comments