[英]ASP.Net MVC with Active Directory Authentication using Owin Middleware
I need to create an ASP.NET MVC 5 application that would use a form (like when using Individual User Accounts) for login but instead of using user info in the database, use the Windows / AD account and credentials. 我需要创建一个ASP.NET MVC 5应用程序,它将使用表单(如使用个人用户帐户时)进行登录,但不使用数据库中的用户信息,而是使用Windows / AD帐户和凭据。
In other words like using Windows Authentication but using an html form instead of the popup Windows authentication usually shows. 换句话说,比如使用Windows身份验证但使用html表单而不是弹出Windows身份验证通常会显示。 Is this possible?
这可能吗?
Ideally authentication would be relegated to IIS and use the same protocols and allow or deny users based on roles. 理想情况下,身份验证将降级到IIS并使用相同的协议,并根据角色允许或拒绝用户。
How can I do this? 我怎样才能做到这一点?
What do I need to configure in the web.config? 我需要在web.config中配置什么?
What do I need to have in Startup.Auth.cs? 我需要在Startup.Auth.cs中拥有什么?
I created a sample project at GitHub called AspNetMvcActiveDirectoryOwin . 我在GitHub上创建了一个名为AspNetMvcActiveDirectoryOwin的示例项目。 You can fork it.
你可以分叉吧。
There are few steps you will want to following - 您需要遵循以下几个步骤 -
First of all, you want to authenticate with Active Directory. 首先,您要使用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;
}
}
Second, you want to create claims which will be used in Owin Middleware. 其次,您要创建将在Owin Middleware中使用的声明。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.