簡體   English   中英

為什么我的聲明在控制器中的用戶中不可見? (ASP.NET WebAPI OWIN自托管)

[英]How come my Claims are not visible in my User in the controller? (ASP.NET WebAPI OWIN Self Hosted)

我將HttpListener設置為允許基本身份驗證和匿名身份驗證。 我還向配置中添加了一個名為AuthenticationHandler的新MessageHandler。

        public void Configuration(IAppBuilder appBuilder)
        {
            var listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
            listener.AuthenticationSchemes = AuthenticationSchemes.Basic | AuthenticationSchemes.Anonymous;

            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();

           //...
            config.MessageHandlers.Add(new AuthenticationHandler());

            appBuilder.UseWebApi(config);
        }

AuthenticationHandlerDelegatingHandler 我將自己的主張,身份和委托人設置如下:

                if (validCredentials)
                {
                    var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, userName),
                        new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password),
                    };

                    var roles = user.Roles.ToString().Split(',');
                    // Make sure to add all the user's roles to the claims
                    claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

                    var identity = new ClaimsIdentity(claims, Scheme);

                    var principal = new ClaimsPrincipal(new [] {identity});

                    Thread.CurrentPrincipal = principal;

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

如果在調試器中檢查Thread.CurrentPrincipal,則我的主體具有我的身份以及所添加的所有聲明。 在DelegatingHandler中,一切似乎都很好,但是這些聲明並未進入我的控制器。

在我的控制器中,我在函數上有一個簡單的[Authorize(Roles="Admin")]屬性。 但是,如果我在調試器中檢查User ,則列出的唯一聲明是用戶名。 因此[Authorize][Authorize(Users="admin')] ,但是,顯然,基於角色的身份驗證將不起作用,我當然可以在數據庫中查找用戶名並手動檢查函數中的角色,但是顯然這不是正確的解決方法。我在做什么錯?

對於OWIN,必須在請求中設置主體,如下所示: request.GetRequestContext().Principal = principal;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM