Add APIKey authentication
This commit is contained in:
43
Program.cs
43
Program.cs
@@ -1,33 +1,64 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using TodoApi.Helpers;
|
||||
using TodoApi.Models;
|
||||
using Microsoft.OpenApi.Models;
|
||||
|
||||
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));
|
||||
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");
|
||||
builder.Services.AddSingleton<IApiKeyValidator, ApiKeyValidator>(_ => new ApiKeyValidator(apiKeys));
|
||||
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
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();
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
// }
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAuthentication();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user