![](/img/trans.png)
[英]How come my Claims are not visible in my User in the controller? (ASP.NET WebAPI OWIN Self Hosted)
[英]Owin Authentication and claims in asp.net how to access user data
我已經閱讀了關於 OWIN、ASP 中的聲明和身份驗證的不同文章,但我仍然無法理解很多東西。
我正在開發一個 Intranet 應用程序,用戶身份驗證基於 Active Directory。 我已經實現了類似的東西
並且它可以完美地通過活動目錄對用戶進行身份驗證。 我添加了將用戶數據存儲在 cookie 中的聲明
private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal)
{
var identity = new ClaimsIdentity(MyAuthentication.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory"));
identity.AddClaim(new Claim(ClaimTypes.Name, userPrincipal.SamAccountName));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userPrincipal.SamAccountName));
identity.AddClaim(new Claim(ClaimTypes.GivenName, userPrincipal.GivenName));
return identity;
}
現在每次我想訪問這些信息時,我都必須編寫以下代碼:
var claimsIdentity = User.Identity as System.Security.Claims.ClaimsIdentity;
var name = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.GivenName);
但是,用戶的用戶名可以通過它自己的身份User.Name
任何人都可以解釋如何以簡單的方式訪問用戶數據,例如 php 中的會話?
您可以使用擴展方法來提供您需要的方法。
using System.Security.Claims;
using System.Security.Principal.IPrincipal;
public static class UserClaimExtentions {
public static string GivenName(this IPrincipal user) {
return user.GetClaimValue(ClaimTypes.GivenName);
}
public static string NameIdentifier(this IPrincipal user) {
return user.GetClaimValue(ClaimTypes.NameIdentifier);
}
public static string GetClaimValue(this IPrincipal user, string name) {
var claimsIdentity = user.Identity as ClaimsIdentity;
return claimsIdentity?.FindFirst(name)?.Value;
}
//If you aren't using the new operators from Roslyn for null checks then
//use this method instead
public static string GetClaimValue(this IPrincipal user, string name) {
var claimsIdentity = user.Identity as ClaimsIdentity;
var claim = claimsIdentity == null ? null : claimsIdentity?.FindFirst(name);
return claim == null ? null : claim.Value;
}
}
現在在您的代碼中,您只需要確保您使用的是定義擴展類的命名空間,然后您就可以執行
var givenName = User.GivenName();
var identifier = User.NameIdentifier();
要么
var givenName = User.GetClaimValue(ClaimTypes.GivenName);
var identifier = User.GetClaimValue(ClaimTypes.NameIdentifier);
如果你想在 Owin 中使用 Windows 身份驗證,你可以從你的 Startup.cs 類中調用它(沒有 cookie 身份驗證):
public void ConfigureAuth(IAppBuilder app)
{
HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
}
然后,無論您擁有OwinContext
您都可以做到
var user = new OwinContext().Authentication.User;
//or
var user = HttpContext.Current.GetOwinContext().Authentication.User;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.