I'm using ASP.NET Core 2.2 and I have a custom Authorize
attribute filter called CustomAuthorize
that handles authentication and authorization. The authentication part is handled manually with some code I've written in the OnAuthorization
function, and the authorization part is taken care of by whatever code is in the AuthorizeAttribute
class, which CustomAuthorize
inherits from.
I want to be able to inject several services into my CustomAuthorize
filter in order to verify that the user's roles have not been changed in the database by comparing them to those in the Role
claims. I found that the way to inject services is to use the ServiceFilterAttribute. When I apply the ServiceFilter
to the CustomAuthorize
attribute like this:
I get the error The name 'Roles' does not exist in the current context
. I understand that ServiceFilter
can't accept constructor arguments for the type (that's the TypeFilter's job) but Role
is just a property on the AuthorizeAttribute
class, as you can see below:
public class AuthorizeAttribute : Attribute, IAuthorizeData
{
public AuthorizeAttribute();
public AuthorizeAttribute(string policy);
public string Policy { get; set; }
public string Roles { get; set; }
public string AuthenticationSchemes { get; set; }
public string ActiveAuthenticationSchemes { get; set; }
}
So, why can't I set the Roles
property for the attribute filter? What am I misunderstanding here?
My CustomAuthorize
filter. I would eventually have a constructor and inject my services into it:
public class CustomAuthorize : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
string redirectUrl = "/UserAccess/Index";
if (context.HttpContext.User.Identity.IsAuthenticated)
{
if (context.HttpContext.User.HasClaim(CustomClaimTypes.UserNotFound, true.ToString()))
{
context.Result = new RedirectResult("/UserAccess/NotAuthorized");
}
}
else
{
if (context.HttpContext.Request.IsAjaxRequest())
{
context.HttpContext.Response.StatusCode = 401;
JsonResult jsonResult = new JsonResult(new { redirectUrl = redirectUrl });
context.Result = jsonResult;
}
else
{
context.Result = new RedirectResult(redirectUrl);
}
}
}
}