【发布时间】:2018-06-29 12:48:31
【问题描述】:
在对 Identity 2.0、模拟、委派和 Kerberos 进行了数周的研究之后,我仍然无法找到一种解决方案来模拟我在 MVC 应用程序中使用 OWIN 创建的 ClaimsIdentity 用户。我的方案的具体情况如下。
禁用 Windows 身份验证 + 启用匿名。
我正在使用 OWIN 启动类针对我们的 Active Directory 手动验证用户身份。然后我将一些属性打包到一个 cookie 中,该 cookie 在应用程序的其余部分都可用。 This 是我在设置这些类时引用的链接。
Startup.Auth.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = MyAuthentication.ApplicationCookie,
LoginPath = new PathString("/Login"),
Provider = new CookieAuthenticationProvider(),
CookieName = "SessionName",
CookieHttpOnly = true,
ExpireTimeSpan = TimeSpan.FromHours(double.Parse(ConfigurationManager.AppSettings["CookieLength"]))
});
AuthenticationService.cs
using System;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;
using System.Security.Claims;
using Microsoft.Owin.Security;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
namespace mine.Security
{
public class AuthenticationService
{
private readonly IAuthenticationManager _authenticationManager;
private PrincipalContext _context;
private UserPrincipal _userPrincipal;
private ClaimsIdentity _identity;
public AuthenticationService(IAuthenticationManager authenticationManager)
{
_authenticationManager = authenticationManager;
}
/// <summary>
/// Check if username and password matches existing account in AD.
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
public AuthenticationResult SignIn(String username, String password)
{
// connect to active directory
_context = new PrincipalContext(ContextType.Domain,
ConfigurationManager.ConnectionStrings["LdapServer"].ConnectionString,
ConfigurationManager.ConnectionStrings["LdapContainer"].ConnectionString,
ContextOptions.SimpleBind,
ConfigurationManager.ConnectionStrings["LDAPUser"].ConnectionString,
ConfigurationManager.ConnectionStrings["LDAPPass"].ConnectionString);
// try to find if the user exists
_userPrincipal = UserPrincipal.FindByIdentity(_context, IdentityType.SamAccountName, username);
if (_userPrincipal == null)
{
return new AuthenticationResult("There was an issue authenticating you.");
}
// try to validate credentials
if (!_context.ValidateCredentials(username, password))
{
return new AuthenticationResult("Incorrect username/password combination.");
}
// ensure account is not locked out
if (_userPrincipal.IsAccountLockedOut())
{
return new AuthenticationResult("There was an issue authenticating you.");
}
// ensure account is enabled
if (_userPrincipal.Enabled.HasValue && _userPrincipal.Enabled.Value == false)
{
return new AuthenticationResult("There was an issue authenticating you.");
}
MyContext dbcontext = new MyContext();
var appUser = dbcontext.AppUsers.Where(a => a.ActiveDirectoryLogin.ToLower() == "domain\\" +_userPrincipal.SamAccountName.ToLower()).FirstOrDefault();
if (appUser == null)
{
return new AuthenticationResult("Sorry, you have not been granted user access to the MED application.");
}
// pass both adprincipal and appuser model to build claims identity
_identity = CreateIdentity(_userPrincipal, appUser);
_authenticationManager.SignOut(MyAuthentication.ApplicationCookie);
_authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, _identity);
return new AuthenticationResult();
}
/// <summary>
/// Creates identity and packages into cookie
/// </summary>
/// <param name="userPrincipal"></param>
/// <returns></returns>
private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal, AppUser appUser)
{
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.GivenName, userPrincipal.GivenName));
identity.AddClaim(new Claim(ClaimTypes.Surname, userPrincipal.Surname));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userPrincipal.SamAccountName));
identity.AddClaim(new Claim(ClaimTypes.Name, userPrincipal.SamAccountName));
identity.AddClaim(new Claim(ClaimTypes.Upn, userPrincipal.UserPrincipalName));
if (!String.IsNullOrEmpty(userPrincipal.EmailAddress))
{
identity.AddClaim(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress));
}
// db claims
if (appUser.DefaultAppOfficeId != null)
{
identity.AddClaim(new Claim("DefaultOffice", appUser.AppOffice.OfficeName));
}
if (appUser.CurrentAppOfficeId != null)
{
identity.AddClaim(new Claim("Office", appUser.AppOffice1.OfficeName));
}
var claims = new List<Claim>();
DirectoryEntry dirEntry = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
foreach (string groupDn in dirEntry.Properties["memberOf"])
{
string[] parts = groupDn.Replace("CN=", "").Split(',');
claims.Add(new Claim(ClaimTypes.Role, parts[0]));
}
if (claims.Count > 0)
{
identity.AddClaims(claims);
}
return identity;
}
/// <summary>
/// Authentication result class
/// </summary>
public class AuthenticationResult
{
public AuthenticationResult(string errorMessage = null)
{
ErrorMessage = errorMessage;
}
public String ErrorMessage { get; private set; }
public Boolean IsSuccess => String.IsNullOrEmpty(ErrorMessage);
}
}
}
那部分似乎工作得很好。但是,在调用数据库时,我需要能够模拟 ClaimsIdentity,因为数据库上有角色级别的安全设置。对于该用户会话的其余部分,我需要在 ClaimsIdentity 的上下文中完成连接。
- 我已经为 Kerberos 设置了 SPN,我知道它可以工作。这个应用程序是 以前使用 Kerberos 委托进行 Windows 身份验证,并且可以正常工作。
- 应用程序池在 SPN 中使用的具有委托权限的服务帐户下运行。
- 我创建的 Identity 对象几乎只在应用程序上下文中使用。我的意思是我主要从 Active Directory 中获取所有必要的属性,但是将从数据库中创建两个。此标识不直接映射到 sql 表或任何其他数据源。
有人可以帮我指出一个示例,在该示例中我可以在对 SQL Server 数据库进行数据库查询时模拟 ClaimsIdentity 对象吗?
【问题讨论】:
标签: c# asp.net-mvc owin kerberos wif