Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom authorization attribute not working in WebAPI

Tags:

 public class CustomAuthorizeAttribute : AuthorizationFilterAttribute  {       protected override bool AuthorizeCore(HttpContextBase httpContext)     {        return true;// if my current user is authorised     }  } 

Above is my CustomAuthorizeAttribute Class and

[CustomAuthorize] // both [CustomAuthorize] and [CustomAuthorizeAttribute ] I tried  public class ProfileController : ApiController {    //My Code.. } 

When I'm calling

http://localhost:1142/api/Profile  

It is not firing CustomAuthorizeAttribute

More over My FilterConfig class is look like below

public class FilterConfig {     public static void RegisterGlobalFilters(GlobalFilterCollection filters)     {                     filters.Add(new CustomAuthorizeAttribute());     } } 

Please help if I miss something.

like image 534
b_in_U Avatar asked Apr 28 '14 10:04

b_in_U


People also ask

How do I create a custom authorization filter in Web API?

To implement a custom authorization filter, we need to create a class that derives either AuthorizeAttribute , AuthorizationFilterAttribute , or IAuthorizationFilter . AuthorizeAttribute : An action is authorized based on the current user and the user's roles.

What is Authorize attribute in Web API?

Using the [Authorize] Attribute Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

How does the Authorize attribute work?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.


1 Answers

  1. Looks like you are using an MVC filter instead of a Web API filter. It can be detected in the sample because it uses HttpContextBase. Instead use the filter from the System.Web.Http.Filters namespace.
  2. You need to override OnAuthorization or OnAuthorizationAsync on the Web API filter.
  3. You don't need to register a global filter and decorate your controller with it. Registering it will make it run for all controllers.

Web API filter code: https://github.com/aspnetwebstack/aspnetwebstack/blob/master/src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs

like image 177
Yishai Galatzer Avatar answered Oct 07 '22 03:10

Yishai Galatzer