refactor: set cookie name to attribute

This commit is contained in:
Polianin Nikita 2024-09-07 04:19:51 +03:00
parent 0ced152fc9
commit 1e204c948c
2 changed files with 5 additions and 3 deletions

View File

@ -9,10 +9,11 @@ namespace Mirea.Api.Endpoint.Common.Attributes;
[AttributeUsage(AttributeTargets.Method)] [AttributeUsage(AttributeTargets.Method)]
public class TokenAuthenticationAttribute : Attribute, IActionFilter public class TokenAuthenticationAttribute : Attribute, IActionFilter
{ {
public const string AuthToken = "AuthToken";
public void OnActionExecuting(ActionExecutingContext context) public void OnActionExecuting(ActionExecutingContext context)
{ {
var setupToken = context.HttpContext.RequestServices.GetRequiredService<ISetupToken>(); var setupToken = context.HttpContext.RequestServices.GetRequiredService<ISetupToken>();
if (!context.HttpContext.Request.Cookies.TryGetValue("AuthToken", out string? tokenFromCookie)) if (!context.HttpContext.Request.Cookies.TryGetValue(AuthToken, out string? tokenFromCookie))
{ {
context.Result = new UnauthorizedResult(); context.Result = new UnauthorizedResult();
return; return;

View File

@ -69,9 +69,10 @@ public class SetupController(
[HttpGet("CheckToken")] [HttpGet("CheckToken")]
public ActionResult<bool> CheckToken([FromQuery] string token) public ActionResult<bool> CheckToken([FromQuery] string token)
{ {
if (!setupToken.MatchToken(Convert.FromBase64String(token))) return Unauthorized("The token is not valid"); if (!setupToken.MatchToken(Convert.FromBase64String(token)))
return Unauthorized("The token is not valid");
Response.Cookies.Append("AuthToken", token, new CookieOptions Response.Cookies.Append(TokenAuthenticationAttribute.AuthToken, token, new CookieOptions
{ {
Path = UrlHelper.GetSubPathWithoutFirstApiName + "api", Path = UrlHelper.GetSubPathWithoutFirstApiName + "api",
Domain = HttpContext.GetCurrentDomain(), Domain = HttpContext.GetCurrentDomain(),