From b969f49eb354e6d9e0576ef977de5c687c77fab3 Mon Sep 17 00:00:00 2001 From: Matt Bishop Date: Sat, 2 Mar 2024 09:23:30 -0500 Subject: [PATCH] Utilize refresh token and exchange for access token at startup --- Program.cs | 50 ++++++++++++++++++++++++++++++++++------ appsettings.json | 2 +- invintory-updater.csproj | 1 + 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/Program.cs b/Program.cs index 9361835..39b8a76 100644 --- a/Program.cs +++ b/Program.cs @@ -2,6 +2,10 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using System.Net.Http.Json; + +const string GoogleApiKey = "AIzaSyDFYtBIYm-Z9HUbMTcB-4vP1FJMm7lX4LA"; +var httpClient = new HttpClient(); var hostBuilder = Host.CreateApplicationBuilder(args); hostBuilder.Configuration.AddUserSecrets(); @@ -11,16 +15,13 @@ var logger = scope.ServiceProvider.GetRequiredService>(); -if (args.Length == 0) -{ - logger.LogError("No operations specified."); +var token = await RetrieveTokenAsync(); +if (token == null) return -1; -} -var token = hostBuilder.Configuration["AuthorizationToken"]; -if (string.IsNullOrEmpty(token) || token == "SECRET") +if (args.Length == 0) { - logger.LogError("No authorization token secret provided."); + logger.LogError("No operations specified."); return -1; } @@ -43,6 +44,41 @@ return 0; +async Task RetrieveTokenAsync() +{ + var refreshToken = hostBuilder.Configuration["RefreshToken"]; + if (string.IsNullOrEmpty(refreshToken) || refreshToken == "SECRET") + { + logger.LogError("No refresh token secret provided."); + return null; + } + + try + { + using HttpResponseMessage response = await httpClient.PostAsync( + $"https://securetoken.googleapis.com/v1/token?key={GoogleApiKey}", + new FormUrlEncodedContent(new Dictionary + { + ["grant_type"] = "refresh_token", + ["refresh_token"] = refreshToken + })); + response.EnsureSuccessStatusCode(); + + var tokenResponse = await response.Content.ReadFromJsonAsync>(); + if (tokenResponse == null || tokenResponse["access_token"] == null) + { + return null; + } + + return tokenResponse["access_token"]; + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to authorize."); + return null; + } +} + void UpdateCollectionPrices() { // TODO diff --git a/appsettings.json b/appsettings.json index 1fcefce..2331725 100644 --- a/appsettings.json +++ b/appsettings.json @@ -1,3 +1,3 @@ { - "AuthorizationToken": "SECRET" + "RefreshToken": "SECRET" } diff --git a/invintory-updater.csproj b/invintory-updater.csproj index 844694b..900ef00 100644 --- a/invintory-updater.csproj +++ b/invintory-updater.csproj @@ -18,6 +18,7 @@ +