I'm trying to authenticate APIkeys through the header of my API rather than sending it as a query parameter in my controller. I've tried this method and I'm a bit lost of what to do right now. My APIkeys are currently stored in an Entity framework and the header should be able to authenticate them before letting the user do any CRUDs
using System.Threading.Tasks;
using FygiEye.DB.Authentication;
using FygiEye.Settings;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
namespace FygiEye.Middlewares
{
public class AuthentificatePublicAPIMiddleware
{
private const string AuthenticationHeaderKey = "auth-key";
private readonly AuthenticationService authentificationService;
private readonly RequestDelegate next;
public AuthentificatePublicAPIMiddleware(RequestDelegate next, AuthenticationService authentificationService)
{
this.next = next;
this.authentificationService = authentificationService;
}
public async Task Invoke(HttpContext httpContext)
{
//#if DEBUG
// await next.Invoke(httpContext);
// return;
//#endif
// ReSharper disable once HeuristicUnreachableCode
#pragma warning disable 162
if (httpContext.Request.Headers.ContainsKey(AuthenticationHeaderKey))
{
if (httpContext.Request.Headers[AuthenticationHeaderKey].ToString() == AuthenticationHeaderKey)
{
await authentificationService.Authenticate(AuthenticationHeaderKey);
await next.Invoke(httpContext);
return;
}
}
else if (httpContext.Request.Headers.ContainsKey("Authorization"))
{
if (httpContext.Request.Headers["Authorization"].ToString().Contains("Authorization"))
{
await next.Invoke(httpContext);
return;
}
}
httpContext.Response.StatusCode = 401;
await httpContext.Response.WriteAsync("Token is missing or invalid");
return;
#pragma warning restore 162
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class AuthentificatePublicApiMiddlewareExtensions
{
public static IApplicationBuilder UseAuthentificatePublicAPIMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AuthenticationService>();
}
}
}
question from:
https://stackoverflow.com/questions/65951927/how-do-i-authenticate-my-header-token-in-c-sharp-api 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…