Skip to content
Snippets Groups Projects
Commit 0ccc00df authored by Tamara Čierniková's avatar Tamara Čierniková
Browse files

Resolve "Authentication middleware"

parent c7ca29ee
No related branches found
No related tags found
2 merge requests!21Milestone-1,!13Resolve "Authentication middleware"
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
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();
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment