gpt4 book ai didi

c# - 从 ad lds 实例验证 asp.net mvc 5 应用程序

转载 作者:行者123 更新时间:2023-11-30 16:55:06 32 4
gpt4 key购买 nike

您好,我想将 LDAP(安装在 Windows 8.1 机器上的 AD LDS)表单例份验证集成到我的 mvc 5 应用程序中。
我不知道我是否遗漏了 web.config 上的某些内容,或者我的 C# 代码有误,但我已从 ldp.exe 和 ADSI 编辑成功连接为具有管理员权限的用户=管理员,如此处所示 Connected successfully from ADSI Edit with User=Admin with Administrator Privileges

在我的网络配置中,我添加了这些行:

<connectionStrings>
<add name="ADWEB" connectionString="LDAP://M0I:389/CN=Users,CN=Elise,DC=App,DC=com" />
</connectionStrings>
<system.web>
<authentication mode="Forms">
<forms name=".AuthCookie" loginUrl="~/Login/Login" defaultUrl="~/home/index" timeout="10" path="/" requireSSL="false" slidingExpiration="true"
cookieless="UseCookies" domain=""
enableCrossAppRedirects="false" >
<credentials passwordFormat="SHA1" />
</forms>
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
<membership defaultProvider="MyDSProvider">
<providers>
<clear />

<add name="MyDSProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" applicationName="LDAP"
connectionStringName="ADWEB"
connectionUsername="CN=Admin,CN=Users,CN=Elise,DC=App,DC=com"
connectionPassword="Azerty*123"
connectionProtection="None" enableSearchMethods="True" />
</providers>
</membership>

<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>

我的登录方法注意我正在传递 (txtDomainName=App.com, txtUserName=Admin , txtPassword=Azerty*123) :

        [AllowAnonymous]
[HttpGet]

public ActionResult Login ()
{
return View();
}

[AllowAnonymous]
[HttpPost]
public ActionResult Login(string txtDomainName, string txtUserName, string txtPassword)
{
// Path to you LDAP directory server.
// Contact your network administrator to obtain a valid path.
string adPath = "LDAP://M0I:389/CN=Elise,DC=App,DC=com";
LDAP.LdapAuthentication adAuth = new LDAP.LdapAuthentication(adPath);

string error;
try
{
if (true == adAuth.IsAuthenticated(txtDomainName,
txtUserName,
txtPassword))
{
// Retrieve the user's groups
string groups = adAuth.GetGroups();
// Create the authetication ticket
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(1, // version
txtUserName,
DateTime.Now,
DateTime.Now.AddMinutes(60),
false, groups);
// Now encrypt the ticket.
string encryptedTicket =
FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
// Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);

// Redirect the user to the originally requested page
Response.Redirect(
FormsAuthentication.GetRedirectUrl(txtUserName,
false));
}
else
{
error =
"Authentication failed, check username and password.";

}
}
catch (Exception ex)
{
error = "Error authenticating. " + ex.Message;

}

return RedirectToAction("Index","Home");
}

她是我在登录操作中使用的 LdapAuthentification 类

using System.Text;
using System.Collections;
using System.DirectoryServices;
using System;

namespace LDAP.LDAP
{
class LdapAuthentication

{
private string _path;
private string _filterAttribute;
public LdapAuthentication(string path)
{
_path = path;
}

public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path,
domainAndUsername,
pwd);

try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}


public string GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try
{
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
String dn;
int equalsIndex, commaIndex;

for (int propertyCounter = 0; propertyCounter < propertyCount;
propertyCounter++)
{
dn = (String)result.Properties["memberOf"][propertyCounter];

equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1),
(commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " +
ex.Message);
}
return groupNames.ToString();
}

}
}

请注意,我遇到的异常是该行的无效用户名或密码:

Object obj = entry.NativeObject;

$exception {"Le nom d’utilisateur ou le mot de passe est incorrect.\r\n"} System.Exception {System.DirectoryServices.DirectoryServicesCOMException}

最佳答案

我终于连接到我的 AD LDS 实例,而无需在 web.config 中设置连接字符串以下代码展示了我如何使用 AD LDS 对用户进行身份验证

<authentication mode="Forms">
<forms name=".AuthCookie" loginUrl="~/Login/Login" defaultUrl="~/home/index" timeout="10" path="/" requireSSL="false" slidingExpiration="true"
cookieless="UseCookies" domain=""
enableCrossAppRedirects="false" >
<credentials passwordFormat="SHA1" />
</forms>
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>

然后我将我的登录操作更改为:

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
ViewBag.ReturnUrl = returnUrl;

return View();
}

登录方式:

[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(string txtUserName, string txtPassword, string returnUrl)
{

string error;
try
{
PrincipalContext context = new PrincipalContext(ContextType.ApplicationDirectory, "M0I:389", "CN=Elise,DC=App,DC=com", ContextOptions.Negotiate);



bool auth = context.ValidateCredentials(
String.Format("CN={0},CN=Users,CN=Elise,DC=App,DC=com",
txtUserName),
txtPassword,
ContextOptions.SimpleBind);
//get all users groups
UserPrincipal user = UserPrincipal.FindByIdentity(context, txtUserName);
if (user != null)
{
PrincipalSearchResult<Principal> authgroups = user.GetAuthorizationGroups();
// do your checking with the auth groups that the user has - against your list
foreach (var item in authgroups)
{
string x = item.Name;
}
}

if (true == auth)
{

// Create the authetication ticket
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(1, // version
txtUserName,
DateTime.Now,
DateTime.Now.AddMinutes(60),
false, "Administrators");
// Now encrypt the ticket.
string encryptedTicket =
FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
// Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);

if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
Response.Redirect(
FormsAuthentication.GetRedirectUrl(txtUserName,false));
}
}
else
{
error =
"Authentication failed, check username and password.";
ModelState.AddModelError(string.Empty, error);
ViewBag.ReturnUrl = returnUrl;

}
}
catch (Exception ex)
{
error = "Error authenticating. " + ex.Message;
ModelState.AddModelError(string.Empty, error);
ViewBag.ReturnUrl = returnUrl;

}

return Redirect(returnUrl);
}

我现在唯一的问题是我无法使用 User.IsInRole 检查当前用户是否是 View 中特定组的成员。

@User.Identity.IsAuthenticated is giving true

@User.IsInRole("Administrators") is giving false

关于c# - 从 ad lds 实例验证 asp.net mvc 5 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29985696/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com