我需要创建一个 ASP.NET MVC 5 应用程序,该应用程序将使用表单(如使用个人用户帐户时)进行登录,但不使用数据库中的用户信息,而是使用 Windows/AD 帐户和凭据。
换句话说,就像使用 Windows 身份验证一样,但使用 html 表单而不是通常显示的弹出式 Windows 身份验证。 这可能吗?
理想情况下,身份验证应委托(delegate)给 IIS 并使用相同的协议(protocol),并根据角色允许或拒绝用户。
我该怎么做?
我需要在 web.config 中配置什么?
我需要在 Startup.Auth.cs 中包含什么?
最佳答案
我在 GitHub 上创建了一个名为 AspNetMvcActiveDirectoryOwin 的示例项目.你可以 fork 它。
您需要执行几个步骤 -
首先,您要使用 Active Directory 进行身份验证。
public class ActiveDirectoryService : IActiveDirectoryService
{
public bool ValidateCredentials(string domain, string userName, string password)
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
return context.ValidateCredentials(userName, password);
}
}
public User GetUser(string domain, string userName)
{
User result = null;
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
var user = UserPrincipal.FindByIdentity(context, userName);
if (user != null)
{
result = new User
{
UserName = userName,
FirstName = user.GivenName,
LastName = user.Surname
};
}
}
return result;
}
}
其次,您要创建将在 Owin 中间件中使用的声明。
public class OwinAuthenticationService : IAuthenticationService
{
private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";
public OwinAuthenticationService(HttpContextBase context)
{
_context = context;
}
public void SignIn(User user)
{
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
};
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignIn(identity);
}
public void SignOut()
{
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignOut(AuthenticationType);
}
}
关于c# - 使用 Owin 中间件进行 Active Directory 身份验证的 ASP.Net MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383287/