ASP.NET authentication is now based on OWIN middleware that can be used on any OWIN-based host. ASP.NET Identity does not have any dependency on System.Web.
I have an AuthorizeAttribute filter where I need to get the current user and add some properties to be retrieved later by action controllers.
The problem is that I have to use the HttpContext which belongs to System.Web. Is there any alternative of HttpContext for Owin?
public class WebApiAuthorizeAttribute : AuthorizeAttribute { public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { base.OnAuthorization(actionContext); Guid userId = new Guid(HttpContext.Current.User.Identity.GetUserId()); ApplicationUserManager manager = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext())) { PasswordHasher = new CustomPasswordHasher() }; ApplicationUser user = await manager.FindByIdAsync(userId); actionContext.Request.Properties.Add("userId", user.LegacyUserId); } }
Note: I found this question, which seems a duplicate, but asks for a solution working for NancyFx project, which is not valid for me.
Similarly, you use HTTPContext Items collection when you are sharing the same information across the different instance based on the user request and that request could be changed for a different request.
The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.
HttpRequest is a subset of HttpContext . In other words, the HttpContext includes the response, the request, and various other data that's not relevant to a specific request or response; such as the web application, cached data, server settings and variables, session state, the authenticated user, etc.
Open Web Interface for . NET (OWIN) defines an abstraction between . NET web servers and web applications. OWIN decouples the web application from the server, which makes OWIN ideal for self-hosting a web application in your own process, outside of IIS.
You can use OwinRequestScopeContext. Which is doing exactly what you are looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With