DavidParks8 / Owin-Authorization

Backport of Asp.Net core's policy based authorization to Asp.Net 4
Other
60 stars 16 forks source link

How can I cast AuthorizationHandlerContext to HttpContext implementing AuthorizationHandler #62

Closed gorums closed 2 years ago

gorums commented 5 years ago
 protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
 {
    // can I do something like this?
     var httpContext = context.Resource as HttpContext;
lavignep007 commented 5 years ago

Hello @gorums,

To my knowledge, the resource is always going to be null in the handler when you are using the ResourceAuthorizeAttribute.

Alternatively, your issue can be solved by replacing your ResourceAuthorizeAttribute in favor of IAuthorizationService. The service can be injected in the controller. Doing so will let you specify anything (including the current HttpContext) to the resource parameter in the AuthorizeAsync method.

According to the doc, the official ASP.NET Core version will let you access the MVC context in the handler when using the AuthorizeAttribute. It does not seem to work in the backport however.

I branched the code locally and worked a fix that will automatically assign the current HttpActionContext for WebAPI or the AuthorizationContext for MVC to the resource when using the ResourceAuthorizeAttribute. However, I would like to discuss the idea with the author before submitting a pull request.

@DavidParks8, let me know if that makes sense or if I am mistaken. I can create a pull request if the proposition is in line with your vision.

Thank you fore reading me through.

gorums commented 5 years ago

Thanks @lavignep007. I injected a HttpContextWrapper to obtain the HttpContext as you suggest and worked, but should be good idea get HttpContext from AuthorizationHandlerContext too.

lavignep007 commented 5 years ago

@gorums, I'm glad it worked.

I have forked the code for now, you will find what you are missing here: https://github.com/lavignep007/Owin-Authorization/tree/contextinhandler

I will submit a pull request if the author is OK with it, until then, you will have to build and host the resulting package yourself for now.

DavidParks8 commented 5 years ago

Please submit the PR! I have no issues with making the library better no matter who does it.

lavignep007 commented 5 years ago

Awesome, I just did!

imaxoi commented 5 years ago

Dear @lavignep007 ,

Thanks for the answer. Could you please expand on this?

Alternatively, your issue can be solved by replacing your ResourceAuthorizeAttribute in favor of IAuthorizationService. The service can be injected in the controller. Doing so will let you specify anything (including the current HttpContext) to the resource parameter in the AuthorizeAsync method.

I am quite new to .NET Framework and making my way through a legacy system. I am not sure how to inject the service in the controller and define policies on it.