authentificate asp.net mvc的5从ADLDS实例应用程序 [英] authentificate asp.net mvc 5 application from adlds instance

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

问题描述

您好我想LDAP集成(在Windows上安装8.1机AD LDS)形成鉴别到我的MVC 5应用程序。结果
I不知道我在想念在web.config中的东西还是我的C#代码是错误的,但我可是从LDP.EXE和ADSI编辑为用户成功连接=管理员谁拥有管理员权限如下所示



在我的web配置我增加这些行:

 <&是connectionStrings GT; 
<添加名称=广告发布网页链接的connectionString =LDAP:// M0I:389 / CN =用户,CN =埃莉斯,DC =应用,DC = COM/>
< /&是connectionStrings GT;
<&的System.Web GT;
<身份验证模式=表格>
<形式的名称=。AuthCookieloginUrl =〜/登录/登录defaultUrl =〜/家/指数超时=10路径=/requireSSL =假slidingExpiration =真
无Cookie =UseCookies域=
enableCrossAppRedirects =false的>
<凭证了passwordFormat =SHA1/>
< /形式GT;
< /认证>
<授权>
<拒绝用户=? />
<让用户=*/>
< /授权>
<会员defaultProvider =MyDSProvider>
<供应商>
<清/>

<添加名称=MyDSProviderTYPE =System.Web.Security.ActiveDirectoryMembershipProvider,
System.Web程序,版本= 2.0.0.0,文化=中立,
公钥= b03f5f7f11d50a3a的applicationName =LDAP
的connectionStringName =广告发布网页链接
connectionUsername =CN =管理员,CN =用户,CN =埃莉斯,DC =应用,DC = com的
connectionPassword = AZERTY * 123
connectionProtection =无enableSearchMethods =真/>
< /供应商>
< /会员>

<编译调试=真targetFramework =4.5.1/>
<的httpRuntime targetFramework =4.5.1/>
< /system.web>



我是通过我的登录方法说明(txtDomainName = App.com,txtUserName =管理员,txtPassword = AZERTY * 123):

  [使用AllowAnonymous] 
[HTTPGET]

公众的ActionResult登录()
{
返回查看();
}

[使用AllowAnonymous]
[HttpPost]
公众的ActionResult登录(字符串txtDomainName,串txtUserName,串txtPassword)
{
/ /路径,你的LDAP目录服务器。
//联系您的网络管理员联系以获得一个有效的路径。
串adPath =LDAP:// M0I:389 / CN =埃莉斯,DC =应用,DC = COM;
LDAP.LdapAuthentication adAuth =新LDAP.LdapAuthentication(adPath);

字符串错误;

{
如果(真== adAuth.IsAuthenticated(txtDomainName,
txtUserName,
txtPassword))
{
//检索用户组
组串= adAuth.GetGroups();
//创建authetication票
的FormsAuthenticationTicket authTicket =
新的FormsAuthenticationTicket(1,//版本
txtUserName,
DateTime.Now,
DateTime.Now .AddMinutes(60),
假,团体);
//现在加密票。
串的encryptedTicket =
FormsAuthentication.Encrypt(authTicket);
//创建一个cookie和加密票证添加到
// cookie的数据。
的HttpCookie authCookie =
新的HttpCookie(FormsAuthentication.FormsCookieName,
的encryptedTicket);
//饼干添加到传出Cookies集合。
Response.Cookies.Add(authCookie);

//将用户重定向到最初请求的页面
的Response.Redirect(
FormsAuthentication.GetRedirectUrl(txtUserName,
假));
}
,否则
{
错误=
验证失败,请检查用户名和密码。

}
}
赶上(异常前)
{
错误= + ex.Message错误认证。

}

返回RedirectToAction(指数,家);
}



她是我使用我的登录操作

 使用System.Text; System.Collections中使用
;使用的System.DirectoryServices
;
使用系统;

命名空间LDAP.LDAP
{
类LdapAuthentication

{
私人字符串_path;
私人字符串_filterAttribute;
公共LdapAuthentication(字符串路径)
{
_path =路径;
}

公共BOOL IsAuthenticated(字符串域名,用户名字符串,字符串PWD)
{
串domainAndUsername =域+ @\+用户名;
的DirectoryEntry条目=新的DirectoryEntry(_path,
domainAndUsername,
PWD);


{
//绑定到本地AdsObject强制认证。
obj对象= entry.NativeObject;
的DirectorySearcher搜索=新的DirectorySearcher(项);
search.Filter =(SAM帐户名=+使用者名称+);
search.PropertiesToLoad.Add(CN);
SearchResult中的结果= search.FindOne();
如果(空==结果)
{
返回false;
}
//更新目录中的$ B $用户B _path = result.Path的新路径;
_filterAttribute =(字符串)result.Properties [CN] [0];
}
赶上(异常前)
{
抛出新的异常(+ ex.Message错误验证用户。);
}
返回真;
}


公共字符串GetGroups()
{
的DirectorySearcher搜索=新的DirectorySearcher(_path);
search.Filter =(CN =+ _filterAttribute +);
search.PropertiesToLoad.Add(成员);
StringBuilder的组名=新的StringBuilder();

{
SearchResult中的结果= search.FindOne();
INT propertyCount = result.Properties [成员]计数。
字符串DN;
INT equalsIndex,commaIndex;

为(INT propertyCounter = 0; propertyCounter< propertyCount;
propertyCounter ++)
{
DN =(字符串)result.Properties [成员] [propertyCounter ];

equalsIndex = dn.IndexOf(=,1);
commaIndex = dn.IndexOf(,,1);
如果(-1 == equalsIndex)
{
返回NULL;
}
groupNames.Append(dn.Substring((equalsIndex + 1),
(commaIndex - equalsIndex) - 1));
groupNames.Append(|);
}
}
赶上(异常前)
{
抛出新的异常(错误获得组名。+
ex.Message);
}
返回groupNames.ToString();
}

}
}

请注意,我有例外是在该行无效usersname或密码:

  obj对象= entry.NativeObject; 

$ {例外乐德NOM utilisateur欧乐德MOT EST过时incorrect.\r\\\
} {System.Exception的} System.DirectoryServices.DirectoryServicesCOMException


解决方案

终于即时通讯连接到我的AD LDS实例,而不在web.config $设置连接字符串b $ b将下面的代码展示如何管理使用AD LDS

 <到authentificate用户;认证模式=表格> 
<形式的名称=。AuthCookieloginUrl =〜/登录/登录defaultUrl =〜/家/指数超时=10路径=/requireSSL =假slidingExpiration =真
无Cookie =UseCookies域=
enableCrossAppRedirects =false的>
<凭证了passwordFormat =SHA1/>
< /形式GT;
< /认证>
<授权>
<拒绝用户=? />
<让用户=*/>
< /授权>

和我改变了我的登陆行动,以这样的:

  [使用AllowAnonymous] 
公众的ActionResult登录(字符串RETURNURL)
{
如果(Request.IsAuthenticated)
{
返回RedirectToAction(指数,家);
}
ViewBag.ReturnUrl = RETURNURL;

返回查看();
}



登录方法:

  [使用AllowAnonymous] 
[HttpPost]
[ValidateAntiForgeryToken]
公众的ActionResult登录(字符串txtUserName,串txtPassword,串RETURNURL)
{

字符串错误;

{
PrincipalContext背景=新PrincipalContext(ContextType.ApplicationDirectory,M0I:389,CN =埃莉斯,DC =应用,DC = COM,ContextOptions.Negotiate);



布尔AUTH = context.ValidateCredentials(
的String.Format(CN = {0},CN =用户,CN =埃莉斯,DC =应用, DC = COM,
txtUserName),
txtPassword,
ContextOptions.SimpleBind);
//获得所有用户群体
UserPrincipal用户= UserPrincipal.FindByIdentity(背景下,txtUserName);
如果(用户!= NULL)
{
PrincipalSearchResult<主> authgroups = user.GetAuthorizationGroups();
//做用户具有在auth组的检查 - 对你的列表
的foreach(VAR在authgroups项)
{
字符串x = item.Name;
}
}

如果(真== AUTH)
{

//创建authetication票
的FormsAuthenticationTicket authTicket =
新的FormsAuthenticationTicket(1,//版本
txtUserName,
DateTime.Now,
DateTime.Now.AddMinutes(60),
假,管理员) ;
//现在加密票。
串的encryptedTicket =
FormsAuthentication.Encrypt(authTicket);
//创建一个cookie和加密票证添加到
// cookie的数据。
的HttpCookie authCookie =
新的HttpCookie(FormsAuthentication.FormsCookieName,
的encryptedTicket);
//饼干添加到传出Cookies集合。
Response.Cookies.Add(authCookie);

如果(string.IsNullOrEmpty(RETURNURL)!)
{
返回重定向(RETURNURL);
}
,否则
{
的Response.Redirect(
FormsAuthentication.GetRedirectUrl(txtUserName,FALSE));
}
}
,否则
{
错误=
验证失败,请检查用户名和密码。
ModelState.AddModelError(的String.Empty,误差);
ViewBag.ReturnUrl = RETURNURL;

}
}
赶上(异常前)
{
错误= + ex.Message错误认证。
ModelState.AddModelError(的String.Empty,误差);
ViewBag.ReturnUrl = RETURNURL;

}

返回重定向(RETURNURL);
}



我唯一的问题是现在,我不能检查当前用户是使用User.IsInRole的观点有一定组的成员。




@ User.Identity.IsAuthenticated是给真正的



@ User.IsInRole(管理员)是提供虚假



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>

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

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.\r\n"}      System.Exception {System.DirectoryServices.DirectoryServicesCOMException}

解决方案

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>

and i changed my login action to this :

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

return View();
}

the login method :

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

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 is giving true

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆