Claims Auth with OWIN Self Hosted WebApi

前端 未结 1 481
陌清茗
陌清茗 2021-02-07 19:28

I am self hosting WebApi with the following configuration:

Visual Studio 2012 / .NET 4.0

public void Configuration(IAppBuilder appBuilder)
{
    var conf         


        
1条回答
  •  执念已碎
    2021-02-07 19:53

    In the message handler, set the principal like this.

    request.GetRequestContext().Principal = principal;
    

    Do not use

    Thread.CurrentPrincipal = principal;
    
    if (HttpContext.Current != null)
        HttpContext.Current.User = principal;
    

    UPDATE

    It has been a while since I worked on .NET 4.0/2012/Web API <2. So, I cannot answer for sure. But with OWIN hosting, principal must be set in the OWIN context. OwinHttpRequestContext sets both Thread.CurrentPrincipal and the principal in OWIN context. By using request.GetRequestContext().Principal, these details are hidden from you. To make long story short, I believe if you some how set the principal in OWIN context, this will work. Not sure how you can do that from web API message handler. You can do that from OWIN middleware.

    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        config.Routes.MapHttpRoute("default", "api/{controller}/{id}");
    
        //config.MessageHandlers.Add(new PresharedKeyAuthorizer());
    
        app.Use((IOwinContext context, Func next) =>
        {
            var claims = new List();
            claims.Add(new Claim(ClaimTypes.Name, "superstar"));
    
            var identity = new ClaimsIdentity(claims, "PresharedKey");
            var principal = new ClaimsPrincipal(identity);
    
            context.Request.User = principal;
            return next.Invoke();
        });
    
        app.UseWebApi(config);
    }
    

    0 讨论(0)
提交回复
热议问题