kreta/KretaWeb/Security/ApiRoleClaimsAuthorizeAttribute.cs
2024-03-13 00:33:46 +01:00

79 lines
2.8 KiB
C#

using System;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Kreta.BusinessLogic.Security;
using Kreta.Enums;
namespace Kreta.Web.Security
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class ApiRoleClaimsAuthorizeAttribute : AuthorizeAttribute
{
private string[] claimValue;
private bool allowAll;
public ApiRoleClaimsAuthorizeAttribute(bool allowAll = false)
{
this.allowAll = allowAll;
SetInstance(KretaSecurityActions.Demand, new SzerepkorTipusEnum[] { });
}
public ApiRoleClaimsAuthorizeAttribute(params SzerepkorTipusEnum[] claimValue)
{
SetInstance(KretaSecurityActions.Demand, claimValue);
}
public ApiRoleClaimsAuthorizeAttribute(KretaSecurityActions type, params SzerepkorTipusEnum[] claimValue)
{
SetInstance(type, claimValue);
}
private void SetInstance(KretaSecurityActions type, params SzerepkorTipusEnum[] values)
{
claimValue = AuthorizeHelper.ConvertRolesToAuthorizeProperty(type, values);
}
public override void OnAuthorization(HttpActionContext actionContext)
{
if (SkipAuthorization(actionContext))
return;
if (IsAuthorized(actionContext))
return;
HandleUnauthorizedRequest(actionContext);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (HttpContext.Current == null)
return false;
if (HttpContext.Current.User == null)
return false;
var principal = HttpContext.Current.User as ClaimsPrincipal;
if (allowAll)
{
var identity = ClaimManager.GetClaimIdentity();
if (identity == null)
return false;
return principal.Identity.IsAuthenticated;
}
return AuthorizeHelper.CheckRoleAccess(claimValue, principal);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
}
private static bool SkipAuthorization(HttpActionContext actionContext)
{
return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0
|| actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0;
}
}
}