我正在开发一个内部网应用程序,其中用户身份验证是基于Active directory的,并且在处理用户声明的适当方式方面存在问题。
我已经实现了类似的东西。
Using OWIN and Active Directory to authenticate users in ASP.Net MVC 5 application
通过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);但是,用户的用户名可以通过identity it self User.Name...which来获得。
发布于 2016-09-11 20:40:31
您可以使用扩展方法来提供所需的方法。
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);发布于 2017-03-22 03:25:35
如果你想在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;https://stackoverflow.com/questions/39346134
复制相似问题