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

Merge branch '8-authentication-middleware' into 'Milestone-1'

Resolve "Authentication middleware"

Closes #8

See merge request !13
parents 40968b49 0ccc00df
No related branches found
No related tags found
2 merge requests!21Milestone-1,!13Resolve "Authentication middleware"
Pipeline #
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 Api.Middleware;
using DAL.Data; using DAL.Data;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
...@@ -22,7 +23,35 @@ builder.Services.AddControllers(); ...@@ -22,7 +23,35 @@ builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); 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>(); builder.Services.AddExceptionHandler<ExceptionHandlerMiddleware>();
var app = builder.Build(); var app = builder.Build();
...@@ -43,6 +72,8 @@ app.UseHttpsRedirection(); ...@@ -43,6 +72,8 @@ app.UseHttpsRedirection();
app.UseAuthorization(); app.UseAuthorization();
app.UseMiddleware<AuthenticationMiddleware>();
app.MapControllers(); app.MapControllers();
app.Run(); 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