0

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).

2 Answers 2

1

In your domain layer, create an abstraction tailed to that layer, allowing access to those details. Example:

public interface IClaimsProvider
{
   TheClaims Claims { get; }
}

In the startup path of the application, create an implementation of IClaimsProvider that uses the HttpContext to get this data. For instance:

public sealed class HttpContextClaimsProvider : IClaimsProvider
{
    public MyClaims Claims => // pull claims from HttpContext.Current
}

This implementation can be registered in Autofac as follows:

builder.RegisterType<HttpContextClaimsProvider>().As<IClaimsProvider>()
    .SingleInstance();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for you answer. Unfortunately, HttpContext.Current is always null.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.