MireaBackend/Endpoint/Common/Attributes/TokenAuthenticationAttribute.cs

28 lines
973 B
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Mirea.Api.Endpoint.Common.Interfaces;
using System;
namespace Mirea.Api.Endpoint.Common.Attributes;
[AttributeUsage(AttributeTargets.Method)]
public class TokenAuthenticationAttribute : Attribute, IActionFilter
{
public const string AuthToken = "AuthToken";
public void OnActionExecuting(ActionExecutingContext context)
{
var setupToken = context.HttpContext.RequestServices.GetRequiredService<ISetupToken>();
if (!context.HttpContext.Request.Cookies.TryGetValue(AuthToken, out string? tokenFromCookie))
{
context.Result = new UnauthorizedResult();
return;
}
if (setupToken.MatchToken(Convert.FromBase64String(tokenFromCookie))) return;
context.Result = new UnauthorizedResult();
}
public void OnActionExecuted(ActionExecutedContext context) { }
}