1

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

Community
  • 1
  • 1
Jeeva J
  • 3,173
  • 10
  • 38
  • 85

1 Answers1

0

I have found the answer myself.

If add the filter to the global asax, then it will be called for all the controllers and action even if mentioned or not.

So we need to remove the following from global.asax

GlobalConfiguration.Configuration.Filters.Add(new CustomAuthorize());

So now, the custom athorize will be call only when mentioned in the controller or action.

Jeeva J
  • 3,173
  • 10
  • 38
  • 85