【发布时间】:2014-07-31 16:01:05
【问题描述】:
我有一个现有的 ASP.NET 应用程序,它使用 LDAP 进行身份验证,使用 ASP.NET 成员身份进行身份验证和授权。
因此,LDAP 用户可以选择使用他的 LDAP 凭据或 ASP.NET 成员凭据进行身份验证。非 LDAP 用户只能使用 LDAP 凭据进行身份验证。
我现在想创建一个使用类似方法进行身份验证和授权的 Web API 项目。
使用 VS 2013,我创建了一个新的 Web API 项目,该项目使用个人帐户选项进行身份验证。
我已经修改了 Providers\ApplicationOAuthProvider.cs 文件中的 GrantResourceOwnerCredentials 方法。
之前
...
IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
...
之后
...
IdentityUser user;
if (AuthenticateActiveDirectory(context.UserName, context.Password, "MyADDomain"))
{
user = await userManager.FindByNameAsync(context.UserName);
}
else
{
user = await userManager.FindAsync(context.UserName, context.Password);
}
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
...
而AuthenticateActiveDirectory方法是:
private bool AuthenticateActiveDirectory(string userName, string password, string domain)
{
bool validation;
try
{
var lcon = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
var nc = new NetworkCredential(userName, password, domain);
lcon.Credential = nc;
lcon.AuthType = AuthType.Negotiate;
lcon.Bind(nc);
validation = true;
}
catch (LdapException)
{
validation = false;
}
return validation;
}
这可行,但这是最好的方法还是有更好的方法?
【问题讨论】:
标签: c# asp.net authentication asp.net-web-api active-directory