I have the code below for a custom Authorize attribute
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
}
the issue is there is no such thing as HttpContextBase. I have all the httpcontext usings as well but still yells at me. what am i doing wrong?
If we want to write custom logic to authorize the user, I suggest you could consider using AuthorizeAttribute and the IAuthorizationFilter.
The IAuthorizationFilter provide the OnAuthorization method which could write some custom logic to authorize the user.
More details, you could refer to below codes:
public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//Custom code ...
//Return based on logic
context.Result = new UnauthorizedResult();
}
}
Besides, asp.net core recommend using the new policy design. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a "policy" (e.g. [Authorize( Policy = "YouNeedToBe18ToDoThis")].
More details, you could refer to this answer.
You can write the code like this:-
Instead of HttpContextBase you can use AuthorizationFilterContext as mentioned in example.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//your code logic..........
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With