103 lines
2.8 KiB
C#
103 lines
2.8 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Data.Sqlite;
|
|
using TodoApi.Helpers;
|
|
using TodoApi.Models;
|
|
using Microsoft.OpenApi.Models;
|
|
using Newtonsoft.Json;
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
// Add services to the container.
|
|
builder.Services.AddControllers();
|
|
|
|
//Read the SQLite connection string from config file and add a DBContext
|
|
var connectionString = new SqliteConnectionStringBuilder(builder.Configuration.GetConnectionString("TodoDatabase"))
|
|
{
|
|
Mode = SqliteOpenMode.ReadWriteCreate
|
|
}.ToString();
|
|
builder.Services.AddDbContext<TodoContext>(options => options.UseSqlite(connectionString));
|
|
|
|
//setup APIKey validation using apikey.json file
|
|
ApiKeys? apiKeys = null;
|
|
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));
|
|
|
|
//setup CORS if origins were supplied in the config file
|
|
string[]? allowedOrigins = builder.Configuration.GetValue<string[]>("AllowedOrigins");
|
|
if (allowedOrigins != null)
|
|
{
|
|
builder.Services.AddCors(options =>
|
|
{
|
|
options.AddPolicy(name: "AllowedOrigins",
|
|
policy =>
|
|
{
|
|
policy.WithOrigins(allowedOrigins);
|
|
});
|
|
});
|
|
}
|
|
|
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
|
builder.Services.AddEndpointsApiExplorer();
|
|
builder.Services.AddSwaggerGen(c =>
|
|
{
|
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ServiceName", Version = "1" });
|
|
c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
|
|
{
|
|
Name = "X-API-KEY",
|
|
In = ParameterLocation.Header,
|
|
Type = SecuritySchemeType.ApiKey,
|
|
Description = "Authorization by X-API-KEY inside request's header",
|
|
Scheme = "ApiKeyScheme"
|
|
});
|
|
|
|
var key = new OpenApiSecurityScheme()
|
|
{
|
|
Reference = new OpenApiReference
|
|
{
|
|
Type = ReferenceType.SecurityScheme,
|
|
Id = "ApiKey"
|
|
},
|
|
In = ParameterLocation.Header
|
|
};
|
|
|
|
var requirement = new OpenApiSecurityRequirement { { key, new List<string>() } };
|
|
|
|
c.AddSecurityRequirement(requirement);
|
|
});
|
|
|
|
var app = builder.Build();
|
|
|
|
//
|
|
// Configure the HTTP request pipeline.
|
|
//
|
|
|
|
// if (app.Environment.IsDevelopment())
|
|
// {
|
|
app.UseSwagger();
|
|
app.UseSwaggerUI();
|
|
// }
|
|
|
|
if (allowedOrigins != null)
|
|
{
|
|
app.UseCors();
|
|
}
|
|
|
|
app.UseAuthentication();
|
|
|
|
app.UseAuthorization();
|
|
|
|
app.MapControllers();
|
|
|
|
app.Run();
|