At the moment I have to develop a self-hosted ASP.NET Web API 2 with Topshelf and Owin. I use Autofac as IOC container and an OAuth2 authentication with JWT tokens.
In .NET Core/.NET 5 web api's I can get DI access to the claims of the current user via IHttpContextAccessor
.
How can I access the user claims via DI in my .NET Framework Web API using Autofac? (I don't want to access them in the API controller but in domain services).
While @Steven's suggestion will work fine with normal .NET Web API 2 applications, it is not suitable for self-hosted applications with Owin, since HttpContext.Current
is always NULL
there.
Based on @Steven's suggested solution, I was able to solve the problem as follows:
Install the Nuget package OwinRequestScopeContext.
Add app.UseRequestScopeContext();
to the Startup.cs
.
Add a IClaimsProvider
interface to the Domain project:
public interface IClaimsProvider
{
ClaimsPrincipal UserClaims { get; }
}
Add a OwinContextClaimsProvider
class which implements IClaimsProvider
to the startup project:
public class OwinContextClaimsProvider : IClaimsProvider
{
public ClaimsPrincipal UserClaims => OwinRequestScopeContext.Current.Environment["server.User"] as ClaimsPrincipal;
}
Register the ClaimsProvider using Autofac:
builder.RegisterType<OwinContextClaimsProvider>().As<IClaimsProvider>().InstancePerLifetimeScope();
Note: IClaimsProvider.UserClaims
will be NULL
if no user is authenticated.