MireaBackend/Endpoint/Common/Attributes/TokenAuthenticationAttribute.cs

28 lines
973 B
C#
Raw Normal View History

2024-05-28 07:14:17 +03:00
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
{
2024-09-07 04:19:51 +03:00
public const string AuthToken = "AuthToken";
2024-05-28 07:14:17 +03:00
public void OnActionExecuting(ActionExecutingContext context)
{
var setupToken = context.HttpContext.RequestServices.GetRequiredService<ISetupToken>();
2024-09-07 04:19:51 +03:00
if (!context.HttpContext.Request.Cookies.TryGetValue(AuthToken, out string? tokenFromCookie))
2024-05-28 07:14:17 +03:00
{
context.Result = new UnauthorizedResult();
return;
}
if (setupToken.MatchToken(Convert.FromBase64String(tokenFromCookie))) return;
context.Result = new UnauthorizedResult();
}
public void OnActionExecuted(ActionExecutedContext context) { }
}