I have implemented token based authentication. I want to write custom authorize attribute.
The reason behind this is, sometime UserIdentity.GetUserId() gives null.
So to handle this I have written the custom authorize attribute, like the following.
This custom Authorize calls for all the calls (anonymous or authorize call). So I have used the property IsAuthorizeCall to check whether the call is coming from anonymous or authorized.
Can I make the calls like, I want to call this custom authorzie only when I mentioned above method. Otherwise this should not be called.
How can I do that?
public class CustomAuthorize : AuthorizationFilterAttribute
{
public bool IsAuthorizeCall { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
if (IsAuthorizeCall)
{
IdentityHelper IdentityHelper = new IdentityHelper();
if (IdentityHelper.UserId== Guid.Empty)
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
Referenced:
Custom Authorization in Asp.net WebApi - what a mess?
How to Customize ASP.NET Web API AuthorizeAttribute for Unusual Requirements