If you want to authorize access to a WebAPI driver based on the current user's roles and use ASP.NET authentication, you can use the WebAPI AuthorizationAttribute
attribute:
[Authorize(Roles = "RolEdicion")]
public class ValuesController : ApiController
{
...
}
I understand that it is not your case. But if you use ASP.NET authentication and want to do a custom authorization process but based on the current ASP.NET user and their roles, you can create an attribute inheriting from AuthorizeAttribute
, this way you will already have implemented in the class base the possibility of restricting access depending on the user or their roles.
If, on the contrary, as I thought you understand, you want to make a completely customized authorization system, you can create an attribute that inherits from the class AuthorizationFilterAttribute
and overwrite the method OnAuthorization
to implement your access restrictions there.
Something like this:
public class MyAuthorizationAttribute: AuthorizationFilterAttribute
{
private readonly string _permisos;
public MyAuthorizationAttribute(string Permisos)
{
_permisos = Permisos;
}
public override void OnAuthorization(HttpActionContext actionContext)
{
if (!ComprobarPermisos())
{
actionContext.Response=new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
base.OnAuthorization(actionContext);
}
private bool ComprobarPermisos()
{
bool tienePermiso;
// Lógica de comprobación de autorización
// ....
return tienePermiso;
}
}
This code creates an authorization attribute MyAuthorizationAttribute
that accepts an argument Permisos
of type string
.
In the method OnAuthorization
, the private method ComprobarPermisos
is called, which is responsible for deciding whether the user has permission to access the controller or not. If you do not have permission, a status code of 401 (not authorized) is returned.
In the controller it would be enough to decorate the class with the attribute indicating in Permisos
the value to be used:
[MyAuthorization(Permisos:"RolEdicion")]
public class ValuesController : ApiController
{
...
}