<small id='EPnxl'></small><noframes id='EPnxl'>

  • <tfoot id='EPnxl'></tfoot>

      <bdo id='EPnxl'></bdo><ul id='EPnxl'></ul>

      <i id='EPnxl'><tr id='EPnxl'><dt id='EPnxl'><q id='EPnxl'><span id='EPnxl'><b id='EPnxl'><form id='EPnxl'><ins id='EPnxl'></ins><ul id='EPnxl'></ul><sub id='EPnxl'></sub></form><legend id='EPnxl'></legend><bdo id='EPnxl'><pre id='EPnxl'><center id='EPnxl'></center></pre></bdo></b><th id='EPnxl'></th></span></q></dt></tr></i><div id='EPnxl'><tfoot id='EPnxl'></tfoot><dl id='EPnxl'><fieldset id='EPnxl'></fieldset></dl></div>

      <legend id='EPnxl'><style id='EPnxl'><dir id='EPnxl'><q id='EPnxl'></q></dir></style></legend>

      1. 从 adlds 实例验证 asp.net mvc 5 应用程序

        authentificate asp.net mvc 5 application from adlds instance(从 adlds 实例验证 asp.net mvc 5 应用程序)
      2. <i id='9YpJz'><tr id='9YpJz'><dt id='9YpJz'><q id='9YpJz'><span id='9YpJz'><b id='9YpJz'><form id='9YpJz'><ins id='9YpJz'></ins><ul id='9YpJz'></ul><sub id='9YpJz'></sub></form><legend id='9YpJz'></legend><bdo id='9YpJz'><pre id='9YpJz'><center id='9YpJz'></center></pre></bdo></b><th id='9YpJz'></th></span></q></dt></tr></i><div id='9YpJz'><tfoot id='9YpJz'></tfoot><dl id='9YpJz'><fieldset id='9YpJz'></fieldset></dl></div>

                <tbody id='9YpJz'></tbody>

              • <bdo id='9YpJz'></bdo><ul id='9YpJz'></ul>
                <tfoot id='9YpJz'></tfoot>

                <small id='9YpJz'></small><noframes id='9YpJz'>

                <legend id='9YpJz'><style id='9YpJz'><dir id='9YpJz'><q id='9YpJz'></q></dir></style></legend>

                  本文介绍了从 adlds 实例验证 asp.net mvc 5 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

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

                  Hi i want to integrate LDAP(AD LDS installed on windows 8.1 machine) forms authentification to my mvc 5 application .
                  i don't know if i m missing something on the web.config or my c# code is wrong but i m connected successfully from ldp.exe and ADSI Edit as User=Admin who have Administrator Privileges as shown here

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

                  in my web config i added those line :

                  <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):

                  my login method note that i'm passing (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 类

                  her is the LdapAuthentification class that i'm using on my login action

                  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();
                      }
                  
                  }
                  }
                  

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

                  Note that the Exception that i have is invalid usersname or password on that line :

                  Object obj = entry.NativeObject;
                  
                  $exception  {"Le nom d’utilisateur ou le mot de passe est incorrect.
                  "}      System.Exception {System.DirectoryServices.DirectoryServicesCOMException}
                  

                  推荐答案

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

                  finally i m connected to my AD LDS Instance without setting connection string in the web.config the following code show how i managed to authentificate user using 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 检查当前用户是否是视图上某个组的成员.

                  my only problem now is that i can't check if the current users is member of a certain groups on the view using User.IsInRole .

                  @User.Identity.IsAuthenticated 是真实的

                  @User.Identity.IsAuthenticated is giving true

                  @User.IsInRole("Administrators") 是假的

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

                  这篇关于从 adlds 实例验证 asp.net mvc 5 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Adding and removing users from Active Directory groups in .NET(在 .NET 中的 Active Directory 组中添加和删除用户)
                  set equality in linq(在 linq 中设置相等)
                  HashSet conversion to List(HashSet 转换为 List)
                  How to set timeout for webBrowser navigate event(如何为 webBrowser 导航事件设置超时)
                  Test whether two IEnumerablelt;Tgt; have the same values with the same frequencies(测试两个IEnumerablelt;Tgt;具有相同频率的相同值)
                  How do you determine if two HashSets are equal (by value, not by reference)?(您如何确定两个 HashSet 是否相等(按值,而不是按引用)?)
                    <tbody id='Luldk'></tbody>
                      • <bdo id='Luldk'></bdo><ul id='Luldk'></ul>

                        1. <i id='Luldk'><tr id='Luldk'><dt id='Luldk'><q id='Luldk'><span id='Luldk'><b id='Luldk'><form id='Luldk'><ins id='Luldk'></ins><ul id='Luldk'></ul><sub id='Luldk'></sub></form><legend id='Luldk'></legend><bdo id='Luldk'><pre id='Luldk'><center id='Luldk'></center></pre></bdo></b><th id='Luldk'></th></span></q></dt></tr></i><div id='Luldk'><tfoot id='Luldk'></tfoot><dl id='Luldk'><fieldset id='Luldk'></fieldset></dl></div>

                          1. <small id='Luldk'></small><noframes id='Luldk'>

                          2. <legend id='Luldk'><style id='Luldk'><dir id='Luldk'><q id='Luldk'></q></dir></style></legend>

                            <tfoot id='Luldk'></tfoot>