我假設您將使用Active Directory進行身份驗證。如果是這樣,您可以使用PrincipalContext和OWIN中間件。
我在GitHub上創建了一個名爲AspNetMvcActiveDirectoryOwin的示例項目。你可以分叉它並運行它。 它最初是爲ASP.Net MVC編寫的,但您也可以使用ASP.Net Web API的相同業務邏輯。
您需要遵循幾個步驟。首先,您要使用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);
}
}
來源
2017-02-23 21:05:18
Win
這是ASP.Net Web窗體還是ASP.Net MVC?你在使用Active Directory嗎? – Win
我打算使用web api?顯然,IWA是他們用於身份驗證的唯一東西? –