Skip to content

Instantly share code, notes, and snippets.

@karthikeyanVK
Last active January 3, 2019 09:24
using System.Security.Claims;
using System.Web.Http.Filters;
public class ClaimsAuthorizeAttribute : AuthorizationFilterAttribute
{
private string claimType;
private string claimValue;
public ClaimsAuthorizeAttribute(string claimType, string claimValue)
{
this.claimType = claimType;
this.claimValue = claimValue;
}
public override void OnAuthorization
(System.Web.Http.Controllers.HttpActionContext actionContext)
{
ClaimsIdentity claimsIdentity;
var httpContext = actionContext.RequestContext;
if (!(httpContext.Principal.Identity is ClaimsIdentity))
{
return;
}
claimsIdentity = httpContext.Principal.Identity as ClaimsIdentity;
var currentReqClaimValue = claimsIdentity.FindFirst(claimType);
if (currentReqClaimValue == null ||currentReqClaimValue.Value != this.claimValue)
throw new UnauthorizedAccessException("Not authorized to access the api");
base.OnAuthorization(actionContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment