I am making a roles and permissions module in .net mvc with webapi.
The thing is that my authorize comes from System.Web.Http
And I don't know how to customize it to be able to use my database permissions to access controller and controller methods.
Something like this: Authorize[Permissions=1] or Authorize[Permissions="EditarRol"] put it
Thanks in advance
If you want to authorize access to a WebAPI controller based on the current user's roles and you use ASP.NET authentication, you can use the
AuthorizationAttribute
WebAPI attribute:I understand that this is not your case. But if you use ASP.NET authentication and you want to make a personalized authorization process but based on the current ASP.NET user and their roles, you can create an attribute inheriting from
AuthorizeAttribute
, in this way you will already have the possibility implemented in the base class to restrict access based on the user or their roles.If, on the other hand, as I have understood, you want to make a completely personalized authorization system, you can create an attribute that inherits from the class
AuthorizationFilterAttribute
and override the methodOnAuthorization
to implement your access restrictions there.Something like that:
This code creates an authorization attribute
MyAuthorizationAttribute
that accepts an argumentPermisos
of typestring
. In the methodOnAuthorization
, the private method is called,ComprobarPermisos
which is in charge of deciding if the user has permission to access the controller or not. In case of not having permission, a status code 401 (unauthorized) is returned.In the controller it would be enough to decorate the class with the attribute indicating
Permisos
the value to use: