diff --git a/Api/Middleware/AuthenticationMiddleware.cs b/Api/Middleware/AuthenticationMiddleware.cs new file mode 100644 index 0000000000000000000000000000000000000000..db55a7c5c189b84f120a2cfb2f738edbdc8a02d9 --- /dev/null +++ b/Api/Middleware/AuthenticationMiddleware.cs @@ -0,0 +1,24 @@ +namespace Api.Middleware; + +public class AuthenticationMiddleware +{ + private readonly string _token = "token"; + private readonly RequestDelegate _next; + + public AuthenticationMiddleware(RequestDelegate next) + { + _next = next; + } + + public async Task Invoke(HttpContext context) + { + if (context.Request.Headers["Authorization"] != _token) + { + context.Response.StatusCode = 401; + return; + } + + await _next(context); + } + +} \ No newline at end of file diff --git a/Api/Program.cs b/Api/Program.cs index e5222e5602b770b877a7cae32aaa912debe1ecc0..975ebbc36ca1e12fcce5487c27ac310052e02803 100644 --- a/Api/Program.cs +++ b/Api/Program.cs @@ -1,6 +1,7 @@ using Api.Middleware; using DAL.Data; using Microsoft.EntityFrameworkCore; +using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); @@ -22,7 +23,35 @@ builder.Services.AddControllers(); // 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 = "Your API", Version = "v1" }); + + // Configure Swagger to accept a static token + c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + Description = "Enter the API key as follows: Bearer YourHardcodedToken", + Name = "Authorization", + In = ParameterLocation.Header, + Type = SecuritySchemeType.ApiKey, + Scheme = "Bearer" + }); + + c.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + } + }, + new string[] {} + } + }); +}); builder.Services.AddExceptionHandler<ExceptionHandlerMiddleware>(); var app = builder.Build(); @@ -43,6 +72,8 @@ app.UseHttpsRedirection(); app.UseAuthorization(); +app.UseMiddleware<AuthenticationMiddleware>(); + app.MapControllers(); app.Run();