Custom Authorize Attribute not working

Jai Holloway 60 Reputation points
2024-08-07T10:51:57.9833333+00:00

I have tried the following two methods of custom authorization, but neither attribute is firing when the endpoint is called in a .NET CORE Web API.

using System.Web.Http;
using System.Web.Http.Controllers;

namespace GlobalTouringV2.Helpers
{
	public class AuthoriseWorksheet : AuthorizeAttribute
	{
		
		public override void OnAuthorization(HttpActionContext actionContext)
		{


			//string authHeader = httpContext.Request.Headers["Authorise"];
			var authHeader = actionContext.Request.Headers.First(x => x.Key == "Authorization");


			string token = authHeader.Value.First();

			try 			
			{ 				
				if (token != "SOMEVALUE") 				
				{ 					
					actionContext.Response = 
					new HttpResponseMessage(HttpStatusCode.Unauthorized); 				
				} 			
			} 			
			catch (Exception) 			
			{ 				
				actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); 			
			}  			
			return;  		
		} 	
	} 
} 


using System.Net;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace GlobalTouringV2.Helpers
{
	public class TokenFilter : AuthorizationFilterAttribute, IAuthorizationFilter
	{
		public override void OnAuthorization(HttpActionContext actionContext)
		{
			var authHeader = actionContext.Request.Headers.First(x => x.Key == "Authorization");


			string token = authHeader.Value.First();

			try 			
			{ 				
				if (token != "SOMEVALUE") 				
				{
 					actionContext.Response = 
						new HttpResponseMessage(HttpStatusCode.Unauthorized); 				
				} 			
			} 			
			catch (Exception) 			
			{ 				
				actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); 								 
			}  			
			return; 		
		} 	
	} 
}


I do not understand why the attributes do not fire. I have sent a request without an Authorization header and the endpoint still works, the attribute breakpoint never gets hit. I don't know what I am doing wrong. Any help would be appreciated

Developer technologies ASP.NET ASP.NET Core
{count} votes

Accepted answer
  1. Anonymous
    2024-08-08T02:22:03.4666667+00:00

    Hi Jai Holloway

    That is because you use the wrong namespace and wrong implements. You may mix ASP.NET Core and ASP.NET. In ASP.NET Core, You need custom Microsoft.AspNetCore.Authorization.AuthorizeAttribute instead of System.Web.Http.AuthorizeAttribute.

    Reference: Custom Authorization attributes

    From your code design, I suggest you implement a custom authorize attribute using IAuthorizationFilter in ASP.NET Core:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    namespace 
    {
        public class AuthoriseWorksheet : Attribute, IAuthorizationFilter
        {
            public void OnAuthorization(AuthorizationFilterContext context)
            {
                if (context.HttpContext.Request.Headers.TryGetValue("Authorization", out var authHeaderValues))
                {
                    string token = authHeaderValues.FirstOrDefault();
                    if (!string.IsNullOrEmpty(token))
                    {
                        try
                        {
                            if (token != "SOMEVALUE")
                            {
                                context.Result = new UnauthorizedResult();
                            }
                        }
                        catch (Exception)
                        {
                            context.Result = new UnauthorizedResult();
                        }
                    }
                    else
                    {
                        context.Result = new UnauthorizedResult();
                    }
                }
                else
                {
                    context.Result = new UnauthorizedResult();
                }
            }
        }
    }
    

    Then you can use it like what you did:

    [HttpPost] 
    [Route("/api/WorkSheet/SubmitGross")] 
    [AuthoriseWorksheet] 
    public IActionResult SubmitGross([FromBody]WorkSheetGross ws) 
    {}
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.