Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Extending the Authenticate Attribute (ASP.NET Core 6)

I need to add a flag into the request HttpContext.Items.Add("Flag","FlagValue") after the user authenticates. I have done similar tasks like this using a separate ActionFilterAttribute but wanted to do in by extending or overriding the AuthorizeAttribute.

I know this can be done using by creating a custom authorize attribute and I've looked at a lot of examples online but the sample I've found doesn't seem to work in ASP.NET Core 6 MVC.

I started something simple to see if it authenticates

[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class AuthorizeUserAttribute : AuthorizeAttribute  
{
    public AuthorizeUserAttribute() 
    {
        Log.Information("Authenticated?"); // stops here
    }

    public AuthorizeUserAttribute(string policy) : base(policy) 
    {
        Log.Information("Authenticated?"); // doesn't stop here
    }
}

and is getting authenticated and checking on the Policies I've created.

[CheckIsAppLocked]
[HttpGet("connections")]
[AuthorizeUser(Policy = "App_User")]
public ActionResult<Packet<List<SFTP_Conn_Info>>> GetConnInfo() 
{
    return OK(HomeLogic.GetConnInfo());
}

My problem is that I cannot tap into the HttpContext class. I don't know the methods I can expose with AuthorizeAttribute, I even tried using the HttpContextAccessor class but it returns null (but when used with the an action filter is not null)

I can call in the action filter OnActionExecuting(ActionExecutingContext actionContext) and reference the actionContext.HttpContext class.

my guess there is a method I need to define in my AuthorizeAttribute but not sure which one is supported in .NET 6.

Help appreciated!

like image 848
kimosavi Avatar asked Dec 03 '25 04:12

kimosavi


1 Answers

If you implement the IActionFilter interface on your defined attribute, you should be able to access the HttpContext as you've mentioned from the declared attribute on your actions.

like image 170
James Croft Avatar answered Dec 05 '25 21:12

James Croft