0

我正在开发一个 ASP.Net 4.0 Web 应用程序,需要允许匿名访问所有页面,但是我想添加由 Active Directory 支持的表单身份验证,以便在用户登录时显示其他(特权)内容。我已经在互联网上搜寻如何执行此操作的示例,但空手而归。

这是我到目前为止所拥有的,但它似乎不起作用......当我点击登录时,它会重定向到主页,我可以使用 Cookies Manager+ 来查看 cookie 已创建,但它仍然显示匿名模板。我想我可能会搞错这一切......无论如何要修复我必须让它工作的东西,或者有没有我工作过的这种类型的身份验证的例子?

LdapAuthentication.cs

public class LadpAuthentication
{
    private string _path;
    private string _filterAttribute;

    public LadpAuthentication( 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;
    }
}

登录.aspx.cs

    protected void Page_Load( object sender, EventArgs e )
    {

        if( null != Request["logout"] )
        {
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];
            authCookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(authCookie);
            Response.Redirect("~/Default.aspx");
            return;
        }

        string username = Request["username"];
        string password = Request["password"];

        if( username != null && password != null )
        {
            LadpAuthentication ldap = new LadpAuthentication(ConfigurationManager.AppSettings["LogonServer"]);
            if( ldap.IsAuthenticated("mydomain", username, password) )
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(60), false, null);
                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                Response.Cookies.Add(authCookie);
                Response.Redirect("~/Default.aspx");
            }
            else
                test.Text = "Invalid username and/or password.";
        }
    }

登录.aspx

<asp:Label ID="test" runat="server" />
<form action="<%= ResolveClientUrl("~/Login.aspx") %>" method="post">
    <label for="username">Username</label><br />
    <input type="text" id="username" name="username" /><br />
    <label for="password">Password:</label><br />
    <input type="password" id="password" name="password" /><br />
    <input type="submit" value="Login" />
</form>

Global.asax.cs void Application_AuthenticateRequest(对象发送者,EventArgs e){

        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = Context.Request.Cookies[cookieName];

        if( null == authCookie )
            return;
        try {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            GenericIdentity gid = new GenericIdentity(authTicket.Name, "LdapAuthentication");
            Context.User = new GenericPrincipal(gid,null);
        } catch( Exception ex ) {

        }
    }

默认.aspx

<asp:LoginView runat="server">
    <AnonymousTemplate>
        <a id="login-button" href="<%= ResolveClientUrl("~/Login.aspx") %>" class="ui-button">Login</a>
    </AnonymousTemplate>
    <LoggedInTemplate>
        <asp:LoginName runat="server" />
    </LoggedInTemplate>
</asp:LoginView>
4

0 回答 0