kimosavi
kimosavi

Reputation: 111

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!

Upvotes: 3

Views: 1031

Answers (2)

kimosavi
kimosavi

Reputation: 111

[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class AuthorizeUserAttribute : AuthorizeAttribute, IActionFilter {
    public void OnActionExecuted(ActionExecutedContext context) {}
    public void OnActionExecuting(ActionExecutingContext actionContext) {
        actionContext.HttpContext.Items.Add("Flag", GetFlagValue());
    }
}

Upvotes: 1

James Croft
James Croft

Reputation: 1680

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.

Upvotes: 1

Related Questions