Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
230 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use OwinRequestScopeContext. Which is doing exactly what you are looking for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...