jasontaylordev / NorthwindTraders

Northwind Traders is a sample application built using ASP.NET Core and Entity Framework Core.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to access HttpContext information in my services defined in Infrastructure?

despotive opened this issue · comments

Hi

In my Infrastructure project I have to implement a HttpClient that connects to an external API. This API requires the user to be authenticated (through oauth2) and the only implemented flow is the authorization_code one. What I'm doing right now is storing the JWT in a session cookie once the user has authenticated himself.

With that being said, how am I supposed to actually pass the JWT from the controller to the service?

Obviously I could pass the token to every method of the service, but it does feel a bit repetitive and bad to use (especially because not all services that not all implementation of the interface will require this authentication). Another way would be to somehow inject the HttpContext into the services, that way I'll be able to directly retrieve the token from the HttpContext cookie if needed! But I belive it brakes abstraction too (my Infrastructure will have a dependency on Microsoft.AspNetCore.Mvc.ControllerBase).

I'm having a really hard time tackling this issue and would love some input / help. Thanks!

Hey @despotive,

I've solved that previously by creating an ICurrentUserContext interface that's shared between layers, but an JwtCurrentUserContext (or similarly named) class in my controller layer.

The interface defines one or two ways to get the CurrentUser. The JwtCurrentUserContext includes an IHttpContextAccessor injection to get the necessary auth data from the header. Finally, I register using services.AddScoped<ICurrentUserContext, JwtCurrentUserContext>() in ASP.NET Core's Startup.cs.

That makes sens, and it worked for my case, thank you!