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