我在GitHub上创建了一个示例项目,名为AspNetMvcActiveDirectoryOwin。你可以分叉它。
有,你会想以下几个步骤 -
首先,你要与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;
}
}
其次,您要创建将用于欧文中间件的声明。
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);
}
}
来源
2016-11-02 18:52:05
Win
简短回答您提供的信息:是的。有可能的。 – Shyju
@Shyju感谢您的回答,您的评论让我意识到我没有问过如何去做。我会更新这个问题。 – Lastwall
我在MSDN博客https://blogs.msdn.microsoft.com/webdev/2013/07/03/understanding-owin-forms-authentication-in-mvc-5/上发现了以下文章,但似乎没有使用当前版本的ASP.NET MVC,因为代码中引用的对象上不存在方法。 – Lastwall