ariannnn
ariannnn

Reputation: 77

Custom Authorization Attribute in .Net Core 5

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?

Upvotes: 4

Views: 17164

Answers (3)

Ali Ghorbani
Ali Ghorbani

Reputation: 21

The below code worked for me in .Net Core 5

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorization : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        Microsoft.Extensions.Primitives.StringValues tokens;
        context.HttpContext.Request.Headers.TryGetValue("saToken", out tokens);
        var token = tokens.FirstOrDefault();

        if (!string.IsNullOrEmpty(token))
        {
            var jwtService = (IJwtService)context.HttpContext.RequestServices.GetService(typeof(IJwtService));

            if (jwtService.IsValidToken(token))
                return;
            else
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Invalid Token";
                context.Result = new JsonResult("Invalid Token")
                {
                    Value = new { Status = "Unauthorized", Message = "Invalid Token" }
                };
            }
        }
        else
        {
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed;
            context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Please Provide Token";
            context.Result = new JsonResult("Please Provide Token")
            {
                Value = new { Status = "ExpectationFailed", Message = "Please Provide Token" }
            };
        }
    }
}

Upvotes: 2

Shashwat Prakash
Shashwat Prakash

Reputation: 484

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

Upvotes: 2

Brando Zhang
Brando Zhang

Reputation: 28397

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.

Upvotes: 2

Related Questions