Skip to content

Commit

Permalink
Fix expired token (#158)
Browse files Browse the repository at this point in the history
Needed to implement a password provider for the postgres database
connection
Serilog can no longer dump stuff into the database, only can do that
locally where the token won't expire
Also implemented Application Insights, as a way to debug the application
  • Loading branch information
noremacskich authored Oct 9, 2024
1 parent 8d05178 commit 4523f6e
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 28 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/DeployAPI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,4 @@ jobs:
imageToDeploy: ${{ vars.EXPRESSEDREALMSFRONTEND_REGISTRY_URL }}/noremacskich/expressedrealms-api:${{ github.sha }}
containerAppName: ca-expressedrealms-api
resourceGroup: RG_ExpressedRealms
environmentVariables: ASPNETCORE_ENVIRONMENT=secretref:aspnetcore-environment POSTMARK_API_KEY=secretref:postmark-api-key NO_REPLY_EMAIL=secretref:no-reply-email TEST_EMAIL_ADDRESS=secretref:test-email-address AZURE_POSTGRESSQL_CONNECTIONSTRING=secretref:azure-postgresql-connectionstring-6f940 FRONT_END_BASE_URL=secretref:front-end-base-url CLIENT_COOKIE_DOMAIN=secretref:client-cookie-domain AZURE_STORAGEBLOB_RESOURCEENDPOINT=secretref:azure-storageblob-resourceendpoint-08dee
environmentVariables: ASPNETCORE_ENVIRONMENT=secretref:aspnetcore-environment POSTMARK_API_KEY=secretref:postmark-api-key NO_REPLY_EMAIL=secretref:no-reply-email TEST_EMAIL_ADDRESS=secretref:test-email-address AZURE_POSTGRESSQL_CONNECTIONSTRING=secretref:azure-postgresql-connectionstring-6f940 FRONT_END_BASE_URL=secretref:front-end-base-url CLIENT_COOKIE_DOMAIN=secretref:client-cookie-domain AZURE_STORAGEBLOB_RESOURCEENDPOINT=secretref:azure-storageblob-resourceendpoint-08dee APPLICATION_INSIGHTS_CONNECTION_STRING=secretref:application-insights-connection-string

Check failure on line 82 in .github/workflows/DeployAPI.yml

View workflow job for this annotation

GitHub Actions / MegaLinter

82:501 [line-length] line too long (578 > 500 characters)
3 changes: 3 additions & 0 deletions api/ExpressedRealms.Server/ExpressedRealms.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
<PackageReference Include="FluentValidation" Version="11.9.1" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.9.1" />
<PackageReference Include="MicroElements.Swashbuckle.FluentValidation" Version="6.0.0" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.22.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0">
Expand All @@ -27,6 +29,7 @@
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
<PackageReference Include="Serilog.Sinks.PostgreSQL" Version="2.3.0" />
<PackageReference Include="SharpGrip.FluentValidation.AutoValidation.Endpoints" Version="1.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
Expand Down
91 changes: 64 additions & 27 deletions api/ExpressedRealms.Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,42 +22,43 @@
using Unchase.Swashbuckle.AspNetCore.Extensions.Extensions;
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Extensions.AspNetCore.DataProtection.Blobs;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Npgsql;

try
{
Log.Information("Setting Up Web App");
var builder = WebApplication.CreateBuilder(args);

// For system-assigned identity.

string connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? "";
if (string.IsNullOrEmpty(connectionString))
{
var sqlServerTokenProvider = new DefaultAzureCredential();
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]
{
"https://ossrdbms-aad.database.windows.net/.default"
}));

connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_POSTGRESSQL_CONNECTIONSTRING")};Password={accessToken.Token}";
}

Log.Information("Setting Up Loggers");
Log.Logger = new LoggerConfiguration()
var logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console()
.WriteTo.PostgreSQL(
.WriteTo.Console();

if (!string.IsNullOrEmpty(connectionString))
{
logger.WriteTo.PostgreSQL(
connectionString,
"Logs",
needAutoCreateTable: true
)
.CreateLogger();
);
}
else
{
logger.WriteTo.ApplicationInsights(Environment.GetEnvironmentVariable("APPLICATION_INSIGHTS_CONNECTION_STRING"), TelemetryConverter.Traces);
}

Log.Logger = logger.CreateLogger();

builder.Host.UseSerilog();

builder.Services.AddApplicationInsightsTelemetry((options) =>
{
options.ConnectionString = Environment.GetEnvironmentVariable("APPLICATION_INSIGHTS_CONNECTION_STRING");
});

// Since we are in a container, we need to keep track of the data keys manually
var blobStorageEndpoint = Environment.GetEnvironmentVariable("AZURE_STORAGEBLOB_RESOURCEENDPOINT") ?? "";
Expand All @@ -70,18 +71,54 @@
builder.Services.AddDataProtection()
.PersistKeysToAzureBlobStorage(blobClient);
}

Log.Information("Add in Healthchecks");

builder.Services.AddHealthChecks();

Log.Information("Adding DB Context");

builder.Services.AddDbContext<ExpressedRealmsDbContext>(options =>
options.UseNpgsql(connectionString,
x => x.MigrationsHistoryTable("_EfMigrations", "efcore")
)
);
builder.Services.AddDbContext<ExpressedRealmsDbContext>(async (serviceProvider, options) =>
{
if (string.IsNullOrEmpty(connectionString))
{
var dataSourceBuilder = new NpgsqlDataSourceBuilder(Environment.GetEnvironmentVariable("AZURE_POSTGRESSQL_CONNECTIONSTRING"));
dataSourceBuilder.UsePasswordProvider(
passwordProvider: _ =>
{
var sqlServerTokenProvider = new DefaultAzureCredential();
AccessToken accessToken = sqlServerTokenProvider.GetToken(
new TokenRequestContext(new string[] { "https://ossrdbms-aad.database.windows.net/.default" })
);

return accessToken.Token;
},
passwordProviderAsync: async (passwordBuilder, token) =>
{
var sqlServerTokenProvider = new DefaultAzureCredential();
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(new string[] { "https://ossrdbms-aad.database.windows.net/.default" }),
token // Pass the cancellation token along if needed
);

return accessToken.Token;
});
var dataSource = dataSourceBuilder.Build();

options.UseNpgsql(dataSource, postgresOptions =>
{
postgresOptions.MigrationsHistoryTable("_EfMigrations", "efcore");
});
}
else
{
options.UseNpgsql(connectionString, postgresOptions =>
{
postgresOptions.MigrationsHistoryTable("_EfMigrations", "efcore");
});
}

});

Log.Information("Setting Up Authentication and Identity");
builder
Expand Down

0 comments on commit 4523f6e

Please sign in to comment.