Move APIKeys to file and allow read vs read/write

This commit is contained in:
2023-11-23 11:41:58 -05:00
parent 15f8385005
commit a7045ea9a4
12 changed files with 100 additions and 17 deletions

View File

@@ -3,6 +3,7 @@ using Microsoft.Data.Sqlite;
using TodoApi.Helpers;
using TodoApi.Models;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
var builder = WebApplication.CreateBuilder(args);
@@ -16,8 +17,20 @@ var connectionString = new SqliteConnectionStringBuilder(builder.Configuration.G
}.ToString();
builder.Services.AddDbContext<TodoContext>(options => options.UseSqlite(connectionString));
//setup APIKey validation using APIKeys from config file
var apiKeys = builder.Configuration.GetSection("Authentication").GetValue<List<string>>("APIKeys");
//setup APIKey validation using apikey.json file
ApiKeys apiKeys = new();
try
{
string? apiKeyFilename = builder.Configuration.GetValue<string>("APIKeyFile");
if (File.Exists(apiKeyFilename))
{
string jsonText = File.ReadAllText(apiKeyFilename);
ApiKeys? apiKeysTemp = JsonConvert.DeserializeObject<ApiKeys>(jsonText);
if (apiKeysTemp != null) apiKeys = apiKeysTemp;
}
}
catch {}
builder.Services.AddSingleton<IApiKeyValidator, ApiKeyValidator>(_ => new ApiKeyValidator(apiKeys));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle