2016-09-06 63 views
2

我已經閱讀了有關OWIN,聲明和身份驗證的不同文章,但我仍然無法理解大量的東西。Owin在asp.net中的身份驗證和聲明如何訪問用戶數據

我開發的Intranet應用程序是用戶身份驗證基於Active Directory。我已實施類似的東西這個

http://tech.trailmax.info/2016/03/using-owin-and-active-directory-to-authenticate-users-in-asp-net-mvc-5-application/

及其工作完全通過活動目錄用戶進行身份驗證。我已經加入聲稱用戶數據我想訪問這些我都寫了下面的代碼信息,每次都存儲在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會話?

回答

0

您可以使用擴展方法來提供您需要的方法。

using System.Security.Claims; 
using System.Security.Principle.IPrinciple; 

public static class UserClaimExtentions { 

    public static string GivenName(this IPrinciple user) { 
    return user.GetClaimValue(ClaimTypes.GivenName); 
    } 

    public static string NameIdentifier(this IPrinciple user) { 
    return user.GetClaimValue(ClaimTypes.NameIdentifier); 
    } 

    public static string GetClaimValue(this IPrinciple 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 IPrinciple 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); 
0

如果你想用Owin使用Windows Auth,你可以從你的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;