0

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?

ariannnn
  • 27
  • 5
  • The `AuthorizeAttribute` in ASP.Net core has no `AuthorizeCore` method to override, and `HttpContextBase` does not exists. Those are from ASP.Net (not core). This question might help: https://stackoverflow.com/questions/31464359/how-do-you-create-a-custom-authorizeattribute-in-asp-net-core?rq=1 – ESG Apr 26 '21 at 01:40

2 Answers2

0

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.

Brando Zhang
  • 15,923
  • 6
  • 23
  • 48
0

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..........
  }
}