我有一个现有的ASP.NET应用程序,它使用LDAP进行身份验证,使用ASP.NET成员进行身份验证和授权
因此,LDAP用户可以选择使用其LDAP凭据或ASP.NET成员身份凭证进行身份验证 . 非LDAP用户只能使用LDAP凭据进行身份验证 .
我现在想要创建一个Web API项目,该项目使用类似的方法进行身份验证和授权 .
使用VS 2013,我创建了一个新的Web API项目,该项目使用Individual Accounts选项进行身份验证 .
我已经修改了 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;
}
这是有效的,但它是最好的方式还是有更好的方法?
1 回答
没关系 . 想到几件事情:
如果你的林中有多个域(或者曾经支持过),今天用户名isn 't unique across the forest - just the domain. Looks like you'正在键入用户名 .
对于
LdapConnection
,我假设空服务器名称仅用于显示在这里?您可以使用S.DS.AD命名空间为您查找域控制器,而不是对其进行硬编码 .你可能想要
AuthType.Basic
而不是在这里谈判 . 您需要确保您的连接是LDAP / S,因为信用将是明文 .