Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在ASP.net(C#)MVC4中实现LDAP_C#_Asp.net Mvc_Active Directory_Forms Authentication - Fatal编程技术网

在ASP.net(C#)MVC4中实现LDAP

在ASP.net(C#)MVC4中实现LDAP,c#,asp.net-mvc,active-directory,forms-authentication,C#,Asp.net Mvc,Active Directory,Forms Authentication,我最初是在ASP.net应用程序(非MVC)上实现的,但现在我必须转换到MVC,我不知道如何修改我的旧代码。作为参考,我使用的股票网站你得到的申请(需要快速和肮脏),我也缝纫Zurb的基础框架。这也是基于C#的 这是一个行之有效的老办法: LOGIN.ASPX <form id="Login" method="post" runat="server"> <fieldset> <legend>Please log

我最初是在ASP.net应用程序(非MVC)上实现的,但现在我必须转换到MVC,我不知道如何修改我的旧代码。作为参考,我使用的股票网站你得到的申请(需要快速和肮脏),我也缝纫Zurb的基础框架。这也是基于C#的

这是一个行之有效的老办法:

LOGIN.ASPX

<form id="Login" method="post"  runat="server">
          <fieldset>
              <legend>Please login</legend>
                    <asp:Label ID="errorLabel" Runat="server" ForeColor=#ff3300></asp:Label><br>

              <div class="row">
                  <div class="large-12 columns">
                      <label>Domain:</label>
                      <asp:TextBox ID="txtDomain" Runat="server" placeholder="Human Check: Please type WORKGROUP"></asp:TextBox>
                  </div>
              </div>
              <div class="row">
                  <div class="large-12 columns">
                      <label>Username:</label>
                       <asp:TextBox ID=txtUsername Runat="server" ></asp:TextBox>
                  </div>
              </div>
              <div class="row">
                  <div class="large-12 columns">
                      <label>Password:</label>
                        <asp:TextBox ID="txtPassword" Runat="server" TextMode=Password></asp:TextBox><br>
                  </div>
              </div>
              <div class="row">
                  <div class="large-6 columns">
<%--                      <a href="#" class="button" id="btnLogin"  runat="server"  önclick="Login_Click">Submit</a>--%>
                      <asp:Button ID="Button1" Runat="server" Text="Login" OnClick="Login_Click" CssClass="button"></asp:Button>
                  </div>
                  <div class="large-6 columns">
                    <br />
                      <asp:CheckBox ID=chkPersist Runat="server" /> Remember Me                  
                  </div>

              </div>
          </fieldset>
      </form>

请登录
--%>

记得我吗
下面的脚本(同一页)起了作用

<script  runat="server">
void Login_Click(object sender, EventArgs e)
{
  string adPath = "LDAP://DC03/DC=Meowmeow,dc=com"; //Path to your LDAP directory server
  Legend_Forms_Manager.LdapAuthentication adAuth = new Legend_Forms_Manager.LdapAuthentication(adPath);
  try
  {
      if (true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
      {
      string groups = adAuth.GetGroups();

      //Create the ticket, and add the groups.
      bool isCookiePersistent = chkPersist.Checked;
      FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, 
                txtUsername.Text,DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);

      //Encrypt the ticket.
      string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

      //Create a cookie, and then add the encrypted ticket to the cookie as data.
      HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

      if(true == isCookiePersistent)
      authCookie.Expires = authTicket.Expiration;

      //Add the cookie to the outgoing cookies collection.
      Response.Cookies.Add(authCookie);

      //You can redirect now.
      Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
    }
    else
    {
      errorLabel.Text = "Authentication did not succeed. Check user name and password.";
    }
  }
  catch(Exception ex)
  {
    errorLabel.Text = "Error authenticating. " + ex.Message;
  }
}
</script>

无效登录\单击(对象发送者,事件参数e)
{
string adPath=“LDAP://DC03/DC=Meowmeow,DC=com”;//LDAP目录服务器的路径
Legend_Forms_Manager.ldaAuthentication adAuth=新Legend_Forms_Manager.ldaAuthentication(adPath);
尝试
{
if(true==adAuth.IsAuthenticated(txtDomain.Text、txtsername.Text、txtPassword.Text))
{
string groups=adAuth.GetGroups();
//创建票证并添加组。
bool iscookeepersist=chkPersist.Checked;
FormsAuthenticationTicket authTicket=新的FormsAuthenticationTicket(1,
txtUsername.Text,DateTime.Now,DateTime.Now.AddMinutes(60),isCookiePersistent,groups);
//加密票据。
字符串encryptedTicket=FormsAuthentication.Encrypt(authTicket);
//创建cookie,然后将加密票据作为数据添加到cookie中。
HttpCookie authCookie=新的HttpCookie(FormsAuthentication.FormScookeName,encryptedTicket);
if(true==iscookeepersistent)
authCookie.Expires=authTicket.expirement;
//将cookie添加到传出cookies集合。
Response.Cookies.Add(authCookie);
//你现在可以重定向了。
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text,false));
}
其他的
{
errorLabel.Text=“身份验证未成功。请检查用户名和密码。”;
}
}
捕获(例外情况除外)
{
errorLabel.Text=“错误验证。”+例如消息;
}
}
ldapaauthentication.cs

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

namespace Legend_Forms_Manager
{
    public 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, AuthenticationTypes.SecureSocketsLayer);

            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();
        }
    }
}
使用系统;
使用系统文本;
使用系统集合;
使用System.DirectoryServices;
命名空间图例\u窗体\u管理器
{
公共类LDA身份验证
{
私有字符串路径;
私有字符串过滤属性;
公共LDA身份验证(字符串路径)
{
_路径=路径;
}
公共bool已验证(字符串域、字符串用户名、字符串pwd)
{
字符串domainAndUsername=域+@“\”+用户名;
DirectoryEntry=新的DirectoryEntry(_路径、域和用户名、pwd、AuthenticationTypes.SecureSocketsLayer);
尝试
{
//绑定到本机对象以强制身份验证。
object obj=entry.NativeObject;
DirectorySearcher search=新的DirectorySearcher(条目);
search.Filter=“(SAMAccountName=“+username+”);
search.PropertiesToLoad.Add(“cn”);
SearchResult=search.FindOne();
if(null==结果)
{
返回false;
}
//将新路径更新到目录中的用户。
_路径=结果。路径;
_filterAttribute=(字符串)result.Properties[“cn”][0];
}
捕获(例外情况除外)
{
抛出新异常(“验证用户时出错。”+ex.Message);
}
返回true;
}
公共字符串GetGroups()
{
DirectorySearcher search=新的DirectorySearcher(_路径);
search.Filter=“(cn=“+\u filteratAttribute+”);
search.PropertiesToLoad.Add(“memberOf”);
StringBuilder groupNames=新建StringBuilder();
尝试
{
SearchResult=search.FindOne();
int-propertyCount=result.Properties[“memberOf”].Count;
字符串dn;
int equalindex,commaIndex;
for(int-propertyCounter=0;propertyCounter
我包括以下参考资料:

~System.DirectoryServices

我很难在2008年左右的教程中找到任何具有一致性的地方

如果你能帮我。。。我这里什么都有,现在只需要翻译一下,我想

我将.aspx和.cs从旧添加到新,将ADConnectionString添加到web.config,并将令牌添加到.cs和.aspx以防止跨站点脚本编写(这迫使我按照引用进行操作)。现在,您可以进入页面,填写信息,但当您单击“提交”时,页面将变为空白,并且不会执行任何操作。仍然需要帮助