如何使用带有Razor的ASP.NET网页对Active Directory进行身份验证?

时间:2015-02-05 19:37:14

标签: c# asp.net razor active-directory ldap

我正在寻找一个Razor语法示例,该示例将包含在ASP.NET网页的cshtml文件中。我正在寻找的解决方案将排除在Visual Studio中编写C#类。我们的项目不是MVC项目,它是一个Web页面项目。

我需要提示用户输入Intranet Web应用程序的用户名和密码,并使用LDAP查询对Active Directory进行身份验证。

我希望Web矩阵中有一个内置的Helper,例如我已经忽略了(比如WebSecurity助手,但是不是查询数据库,而是查询AD服务器)。

1 个答案:

答案 0 :(得分:0)

知道了。在Web Matrix中,打开NuGet包管理器并安装Novell.Directory.Ldap包。以下是一个示例用法:

@using Novell.Directory.Ldap;
@{
    Validation.RequireField("username", "username is required");
    Validation.RequireField("password", "password is required");

    var username = "";
    var userdn   = "";
    var domain = "domain.com";
    var pwd = "";
    var error = "";

    if (IsPost) {
        if (Validation.IsValid()) {
            username = Request["username"];
            userdn   = "cn=" + username + ",ou=Users,o=INTRANET";
            pwd      = Request["password"];

            try {
                LdapConnection ldapConnection = new LdapConnection();
                ldapConnection.Connect(domain, 389);
                ldapConnection.Bind(userdn, pwd);
            }
            catch (LdapException e) {
                error = e.LdapErrorMessage;
            }
        }
    }
}

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Hello LDAP Page</title>
    </head>
    <body>
        <h1>Hello LDAP Page</h1>
        @if (IsPost) {
            if (error.IsEmpty()) {
                <p>'@username' was successfully authenticated against <i>@domain</i>!</p>
            }
            else {
                <p>error! @error</p>
            }
        }
        else {
            @Html.ValidationSummary()
            <form method="post">
            <fieldset>
                <legend>Login</legend>
                <p><label for="username">Username:</label>
                    <input type="text" name="username" value="" />
                    @Html.ValidationMessage("title")</p>

                <p><label for="password">Password:</label>
                    <input type="password" name="password" value="" />
                    @Html.ValidationMessage("password")</p>

                <p><input type="submit" name="buttonSubmit" value="Login" /></p>
            </fieldset>
            </form> 
        }

    </body>
</html>