Skip to content

Commit

Permalink
trying to use key vault
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthew Herb committed May 6, 2024
1 parent 3f7f761 commit 38c8bc4
Show file tree
Hide file tree
Showing 9 changed files with 185 additions and 22 deletions.
13 changes: 3 additions & 10 deletions PoMad/PoMad.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,11 @@
<UserSecretsId>aspnet-PoMad-d3e2d5e7-1bbb-4efd-9a35-ca370c1fc7ce</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<None Remove="app.db" />
</ItemGroup>

<ItemGroup>
<Content Include="app.db">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Azure.Data.Tables" Version="12.8.3" />
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.3.0" />
<PackageReference Include="Azure.Identity" Version="1.11.2" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="8.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="8.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.3" />
Expand Down
91 changes: 80 additions & 11 deletions PoMad/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
Expand All @@ -7,7 +9,7 @@
using PoMad.Services;
using Radzen;

var builder = WebApplication.CreateBuilder(args);
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
Expand All @@ -25,25 +27,88 @@
})
.AddIdentityCookies();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
string connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();


// Bind Google settings
_ = builder.Services.Configure<GoogleAuthConfig>(builder.Configuration.GetSection("Google"));

_ = builder.Services.AddAuthentication().AddGoogle(googleOptions =>



//string? vaultUriString = builder.Configuration["VaultUri"];
//if (string.IsNullOrEmpty(vaultUriString))
//{
// throw new InvalidOperationException("VaultUri configuration not found.");
//}
//Uri keyVaultEndpoint = new(vaultUriString);
//builder.Configuration.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());

//// Build a secret client
//string keyVaultUrl = "https://pomad.vault.azure.net/";
//SecretClient client = new(new Uri(keyVaultUrl), new DefaultAzureCredential());

//// Retrieve secrets
//Azure.Response<KeyVaultSecret> clientId = client.GetSecret("GoogleClientId");
//Azure.Response<KeyVaultSecret> clientSecret = client.GetSecret("GoogleClientSecret");

//// Configure Google authentication with secrets from Azure Key Vault
//builder.Services.AddAuthentication().AddGoogle(options =>
//{
// options.ClientId = clientId.Value.Value;
// options.ClientSecret = clientSecret.Value.Value;
// options.SignInScheme = IdentityConstants.ExternalScheme;
//});





//string? vaultUriString = builder.Configuration["VaultUri"];
//if (string.IsNullOrEmpty(vaultUriString))
//{
// throw new InvalidOperationException("VaultUri configuration not found.");
//}
//Uri keyVaultEndpoint = new Uri(vaultUriString);
//builder.Configuration.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());

//// Build a secret client
//SecretClient client = new SecretClient(keyVaultEndpoint, new DefaultAzureCredential());

//// Retrieve secrets asynchronously
//var clientId = await client.GetSecretAsync("GoogleClientId");
//var clientSecret = await client.GetSecretAsync("GoogleClientSecret");

//// Configure Google authentication with secrets from Azure Key Vault
//builder.Services.AddAuthentication().AddGoogle(options =>
//{
// options.ClientId = clientId.Value.Value;
// options.ClientSecret = clientSecret.Value.Value;
// options.SignInScheme = IdentityConstants.ExternalScheme;
//});







// Bind Google settings from appsettings.json
builder.Services.Configure<GoogleAuthConfig>(builder.Configuration.GetSection("GoogleAuth"));
builder.Services.AddAuthentication().AddGoogle(googleOptions =>
{
// Resolve Google configuration options
GoogleAuthConfig? googleConfig = builder.Configuration.GetSection("Google").Get<GoogleAuthConfig>();
GoogleAuthConfig googleConfig = builder.Configuration.GetSection("GoogleAuth").Get<GoogleAuthConfig>();

Check warning on line 101 in PoMad/Program.cs

View workflow job for this annotation

GitHub Actions / build

Converting null literal or possible null value to non-nullable type.
googleOptions.ClientId = googleConfig.ClientId;

Check warning on line 102 in PoMad/Program.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
googleOptions.ClientSecret = googleConfig.ClientSecret;
googleOptions.SignInScheme = IdentityConstants.ExternalScheme;
});






builder.Services.AddTransient<DailyDataService>();
builder.Services.AddTransient<EmailService>();
builder.Services.AddTransient<DailyDataService>();
Expand All @@ -65,18 +130,18 @@

builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();

var app = builder.Build();
WebApplication app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
_ = app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
_ = app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
_ = app.UseHsts();
}

app.UseHttpsRedirection();
Expand All @@ -91,3 +156,7 @@
app.MapAdditionalIdentityEndpoints();

app.Run();



// az webapp config appsettings set --name PoMad --resource-group PoMad --settings GoogleAuth:ClientId="732386519629-bqh9gqoq1snfcb6j1fh88j5lscj5v4ht.apps.googleusercontent.com" GoogleAuth:ClientSecret="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"
79 changes: 79 additions & 0 deletions PoMad/Properties/ServiceDependencies/PoMad/secrets1.arm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
{
"$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"resourceGroupName": {
"type": "string",
"defaultValue": "PoMad",
"metadata": {
"_parameterType": "resourceGroup",
"description": "Name of the resource group for the resource. It is recommended to put resources under same resource group for better tracking."
}
},
"resourceGroupLocation": {
"type": "string",
"defaultValue": "eastus",
"metadata": {
"_parameterType": "location",
"description": "Location of the resource group. Resource groups could have different location than resources."
}
},
"resourceLocation": {
"type": "string",
"defaultValue": "[parameters('resourceGroupLocation')]",
"metadata": {
"_parameterType": "location",
"description": "Location of the resource. By default use resource group's location, unless the resource provider is not supported there."
}
}
},
"resources": [
{
"type": "Microsoft.Resources/resourceGroups",
"name": "[parameters('resourceGroupName')]",
"location": "[parameters('resourceGroupLocation')]",
"apiVersion": "2019-10-01"
},
{
"type": "Microsoft.Resources/deployments",
"name": "[concat(parameters('resourceGroupName'), 'Deployment', uniqueString(concat('pomad', subscription().subscriptionId)))]",
"resourceGroup": "[parameters('resourceGroupName')]",
"apiVersion": "2019-10-01",
"dependsOn": [
"[parameters('resourceGroupName')]"
],
"properties": {
"mode": "Incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"resources": [
{
"name": "pomad",
"type": "Microsoft.KeyVault/vaults",
"location": "[parameters('resourceLocation')]",
"properties": {
"sku": {
"family": "A",
"name": "Standard"
},
"tenantId": "bbc1ef8a-6d87-4226-8735-685dd2ce9ca3",
"accessPolicies": [],
"enabledForDeployment": false,
"enabledForDiskEncryption": false,
"enabledForTemplateDeployment": false,
"enableSoftDelete": true,
"softDeleteRetentionInDays": 90,
"enableRbacAuthorization": true
},
"apiVersion": "2016-10-01"
}
]
}
}
}
],
"metadata": {
"_dependencyType": "secrets.keyVault"
}
}
12 changes: 12 additions & 0 deletions PoMad/Properties/serviceDependencies.PoMad.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"dependencies": {
"secrets1": {
"serviceConnectorResourceId": "/subscriptions/[parameters('subscriptionId')]/resourceGroups/[parameters('resourceGroupName')]/providers/Microsoft.Web/sites/PoMad/providers/Microsoft.ServiceLinker/linkers/VaultUri_B35A13F4D9",
"secretStore": "AzureAppSettings",
"resourceId": "/subscriptions/[parameters('subscriptionId')]/resourceGroups/[parameters('resourceGroupName')]/providers/Microsoft.KeyVault/vaults/pomad",
"type": "secrets.keyVault",
"connectionId": "VaultUri",
"dynamicId": null
}
}
}
5 changes: 5 additions & 0 deletions PoMad/Properties/serviceDependencies.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
"mssql1": {
"type": "mssql",
"connectionId": "ConnectionStrings:DefaultConnection"
},
"secrets1": {
"type": "secrets",
"connectionId": "VaultUri",
"dynamicId": null
}
}
}
Binary file removed PoMad/app.db
Binary file not shown.
Binary file removed PoMad/app.db-shm
Binary file not shown.
Binary file removed PoMad/app.db-wal
Binary file not shown.
7 changes: 6 additions & 1 deletion PoMad/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@
},
"AllowedHosts": "*",
"AzureTableStorage": {
"ConnectionString": "your_azure_table_storage_connection_string",
"ConnectionString": "DefaultEndpointsProtocol=https;AccountName=pomad;AccountKey=I31TU2NUVy5M5zoqtfowaLs7pla3e4xfL4zp76i9zlLUsMVQWfQ2YzpRnZ5hWlvLYU7IFoyz2Nd3+AStnhM3vA==;EndpointSuffix=core.windows.net",
"TableName": "DailyData"
},
"SendGrid": {
"ApiKey": "your_sendgrid_api_key",
"FromEmail": "[email protected]",
"FromName": "PoMad"
},
"VaultUri": "https://pomad.vault.azure.net/",
"GoogleAuth": {
"ClientId": "732386519629-bqh9gqoq1snfcb6j1fh88j5lscj5v4ht.apps.googleusercontent.com",
"ClientSecret": "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"
}
}

0 comments on commit 38c8bc4

Please sign in to comment.