如何在 .NET Core 2.0 中使用 PrincipalContext
How to use PrincipalContext in .NET Core 2.0
我在 .NET Core 2.0 中创建了一个 Web 应用程序,我想在其中使用来自命名空间 System.DirectoryServices.AccountManagement
.
的 PrincipalContext
我想像这样在 Active Directory 中再次验证用户:
private static ClaimsIdentity ValidateUser(string userName, string password)
{
var domain = GetDomainByLogin(userName);
using (var pc = new PrincipalContext(ContextType.Domain, domain, null, ContextOptions.Negotiate))
{
if (!pc.ValidateCredentials(userName, password)) return null;
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
if (user == null)
{
throw new Exception(UserNotFound);
}
var id = new ClaimsIdentity();
id.AddClaim(new Claim(JwtClaimTypes.Subject, userName));
id.AddClaim(new Claim(JwtClaimTypes.Name, userName));
var groups = user.GetGroups();
var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Name));
id.AddClaims(roles);
return id;
}
}
如何在 .NET Core 2.0
中使用 PrincipalContext
(System.DirectoryServices.AccountManagement
)?
我在 .NET Core 2.0 中创建了一个 Web 应用程序,我想在其中使用来自命名空间 System.DirectoryServices.AccountManagement
.
PrincipalContext
我想像这样在 Active Directory 中再次验证用户:
private static ClaimsIdentity ValidateUser(string userName, string password)
{
var domain = GetDomainByLogin(userName);
using (var pc = new PrincipalContext(ContextType.Domain, domain, null, ContextOptions.Negotiate))
{
if (!pc.ValidateCredentials(userName, password)) return null;
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
if (user == null)
{
throw new Exception(UserNotFound);
}
var id = new ClaimsIdentity();
id.AddClaim(new Claim(JwtClaimTypes.Subject, userName));
id.AddClaim(new Claim(JwtClaimTypes.Name, userName));
var groups = user.GetGroups();
var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Name));
id.AddClaims(roles);
return id;
}
}
如何在 .NET Core 2.0
中使用 PrincipalContext
(System.DirectoryServices.AccountManagement
)?