从adlds实例validationasp.net mvc 5应用程序
您好我想集成LDAP(安装在Windows 8.1机器上的AD LDS)表格validation到我的mvc 5应用程序。
我不知道我是否遗漏了web.config上的内容或我的c#代码错误但我已成功连接ldp.exe和ADSI编辑为User = Admin,其管理员权限如此处所示
在我的网络配置中我添加了这些行:
我的登录方法请注意我正在传递(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(); } } }
请注意,我拥有的exception是该行上的用户名或密码无效:
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 LDSvalidation用户
我将登录操作更改为:
[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 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检查当前用户是否是视图上某些组的成员。
@ User.Identity.IsAuthenticated给出了真实
@ User.IsInRole(“管理员”)给出错误
- 检测使用ASP.NET应用程序登录计算机的用户
- DirectoryServices UserPrincipal.SetPassword忽略密码策略(密码历史记录)
- 从Active Directory PrincipalContext获取所有用户
- 检索用户的自定义Active Directory属性
- ASP.NET / Active Directory – 支持域用户的自动登录
- UserPrincipals.GetAuthorizationGroups枚举组时发生错误(1301)。 该组的SID无法解决
- 从非域计算机连接到域SQL Server 2005
- ASP.NET – 获取DirectoryEntry / SID的主体/相对标识符(RID)
- 如何在Asp.Net中获取用户的AD用户组?