Skip to content

Commit

Permalink
Utilize refresh token and exchange for access token at startup
Browse files Browse the repository at this point in the history
  • Loading branch information
withinfocus committed Mar 2, 2024
1 parent 7fa97bf commit b969f49
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 8 deletions.
50 changes: 43 additions & 7 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Program>();
Expand All @@ -11,16 +15,13 @@

var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();

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;
}

Expand All @@ -43,6 +44,41 @@

return 0;

async Task<string?> 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<string, string>
{
["grant_type"] = "refresh_token",
["refresh_token"] = refreshToken
}));
response.EnsureSuccessStatusCode();

var tokenResponse = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
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
Expand Down
2 changes: 1 addition & 1 deletion appsettings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"AuthorizationToken": "SECRET"
"RefreshToken": "SECRET"
}
1 change: 1 addition & 0 deletions invintory-updater.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="System.Net.Http.Json" Version="8.0.0" />
</ItemGroup>

</Project>

0 comments on commit b969f49

Please sign in to comment.