其在asp.net web应用与认证的麻烦 [英] Having trouble with authentication in asp.net web application

查看:85
本文介绍了其在asp.net web应用与认证的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证谁是登录到从登录页面我的web应用程序的用户。我用的是本教程为指导,其中pretty太多解释我到底是什么希望做,但是当我的用户名和密码进入,验证是行不通的。请允许我解释一下。

下面是我的HTML中的相关部分。没有什么不寻常的:

 <表ID =form1的=服务器>
< D​​IV CLASS =行>
< D​​IV CLASS = COL-XS-4是H.
    < D​​IV CLASS =表单组>
<输入ID =txtUserName类型=文本=服务器>
< ASP:的RequiredFieldValidator的ControlToValidate =txtUserName
       显示=静态的ErrorMessage =*=服务器
       ID =vUserName/>
< / DIV>
< / DIV>< / DIV>
< D​​IV CLASS =行>
< D​​IV CLASS = COL-XS-4是H.
< D​​IV CLASS =表单组>
        <输入ID =txtUserPassTYPE =密码=服务器>
< ASP:的RequiredFieldValidator的ControlToValidate =txtUserPass
      显示=静态的ErrorMessage =*=服务器
      ID =vUserPass/>
< / DIV>
< / DIV>
< / DIV>
< P>< ASP:标签ID =lblMsg前景色=红=服务器/>< / P>
<输入类型=提交VALUE =登录=服务器ID =cmdLogin>< P>< / P>
< ASP:复选框ID =chkPersistCookie=服务器的AutoPostBack =FALSE/>
< /表及GT;

该页面包含一个用户名和一个按钮进行登录(和记住饼干复选框,但我不认为这是有关我的问题)。

下面是code背后:

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.UI程序;
使用System.Web.UI.WebControls;
使用System.Data.SqlClient的;
使用System.Web.Security;命名空间MRAApplication
{
    公共部分类_1__0__0__0_LoginScreen:System.Web.UI.Page
    {
        保护无效的Page_Load(对象发件人,EventArgs的发送)
        {
            this.cmdLogin.ServerClick + =新System.EventHandler(this.cmdLogin_ServerClick);
        }        私人布尔的ValidateUser(用户名字符串,字符串密码)
        {
            康涅狄格州的SqlConnection;
            CMD的SqlCommand;
            字符串lookupPassword = NULL;            //检查无效的用户名。
            //用户名必须不能为空,且必须在1到15个字符之间。
            如果((空==用户名)||(0 == userName.Length)||(userName.Length→15))
            {
                System.Diagnostics.Trace.WriteLine([的ValidateUser]用户名输入验证失败。);
                返回false;
            }            //检查无效密码。
            //密码不能为空,必须在1到25个字符之间。
            如果((空==密码)||(0 == passWord.Length)||(passWord.Length→25))
            {
                System.Diagnostics.Trace.WriteLine([的ValidateUser]输入密码验证失败。);
                返回false;
            }            尝试
            {
                //与SQL Server管理员咨询一个合适的连接
                //字符串用来连接到您的本地SQL Server。
                康恩=新的SqlConnection(databaseConnect);
                conn.Open();                //创建的SqlCommand从给定的提供的用户名用户表中选择PWD领域。
                CMD =新的SqlCommand(选择用户密码,其中用户@ = userName的,康恩);
                cmd.Parameters.Add(@ username的,System.Data.SqlDbType.VarChar,25);
                。cmd.Parameters [@ username的]值=用户名;                //执行命令和pwd现场提取到lookupPassword字符串。
                lookupPassword =(字符串)cmd.ExecuteScalar();                //清理命令和连接对象。
                cmd.Dispose();
                conn.Dispose();
            }
            赶上(异常前)
            {
                //添加的错误处理进行调试。
                //此错误消息不应该被发回给调用者。
                System.Diagnostics.Trace.WriteLine([的ValidateUser]异常+ ex.Message);
            }            //如果发现没有密码,返回false。
            如果(空== lookupPassword)
            {
                //你可以在这里写失败的登录尝试的事件日志以获取更多的安全性。
                返回false;
            }            //比较lookupPassword和输入密码时,使用的是区分大小写的比较。
            回报(0 ==的String.Compare(lookupPassword,密码,FALSE));        }        私人无效cmdLogin_ServerClick(对象发件人,发送System.EventArgs)
        {
            如果(的ValidateUser(txtUserName.Value,txtUserPass.Value))
            {
                TKT的FormsAuthenticationTicket;
                串cookiestr;
                CK的HttpCookie;
                TKT =新的FormsAuthenticationTicket(1,txtUserName.Value,DateTime.Now,
          DateTime.Now.AddMinutes(30),chkPersistCookie.Checked,自定义数据);
                cookiestr = FormsAuthentication.Encrypt(TKT);
                CK =新的HttpCookie(FormsAuthentication.FormsCookieName,cookiestr);
                如果(chkPersistCookie.Checked)
                    ck.Expires = tkt.Expiration;
                ck.Path = FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(CK);                串strRedirect;
                strRedirect =请求[RETURNURL];
                如果(strRedirect == NULL)
                    strRedirect =Default.aspx的;
                的Response.Redirect(strRedirect,真);
            }
            其他
                的Response.Redirect(1.0.0.0_LoginScreen.aspx,真正的);
        }
     }
    }

现在,我已经测试了我的连接字符串和它的作品。它连接到一个表,其中包含用户名,密码和的UserRole的3列的SQL Server数据库。现在我只是在表中,一个测试条目这里所示。

然而,当我运行应用程序并输入test变成txtUserName和密码进入txtUserPass,然后点击提交,它重定向回到登录页面,这意味着它返回为假,如果(的ValidateUser(txtUserName.Value,txtUserPass.Value))。

如果有人可以帮助我这个错误我会AP preciate它。谢谢你的帮助。 :)


解决方案

  

这是我第一次尝试做身份验证,因此我不完全
  知道如何使用断点来获取返回值。


您想连接到SQL Server之前,硬codeD的用户名和密码进行测试。

 保护无效cmdLogin_ServerClick(对象发件人,发送System.EventArgs)
{
    如果(String.Equals(txtUserName.Value,人johndoe
        StringComparison.InvariantCultureIgnoreCase)及&放大器;
        String.Equals(txtUserPass.Value,123456,
        StringComparison.InvariantCultureIgnoreCase))
    {
        VAR角色=新[] {管理员};        VAR票=新的FormsAuthenticationTicket(1,
            txtUserName.Value,
            DateTime.Now,
            DateTime.Now.AddMinutes(30),
            chkPersistCookie.Checked,
            的string.join(,,角色),
            FormsAuthentication.FormsCookiePath);        VAR饼干=新的HttpCookie(FormsAuthentication.FormsCookieName,
            FormsAuthentication.Encrypt(门票));        如果(chkPersistCookie.Checked)
            cookie.Expires = ticket.Expiration;        Response.Cookies.Add(饼干);        字符串RETURNURL =请求[RETURNURL];
        如果(RETURNURL == NULL)
            RETURNURL =Default.aspx的;
        的Response.Redirect(RETURNURL,真);
    }
    其他
        的Response.Redirect(1.0.0.0_LoginScreen.aspx,真正的);
}

如何创建主体对象

当被要求通过身份验证的用户页面,您需要检索cookie认证票,并创建一个主要对象。

  //的Global.asax.cs
公共类全球:一个HttpApplication
{
    无效Application_AuthenticateRequest(对象发件人,EventArgs的发送)
    {
        的HttpCookie decryptedCookie =
            Context.Request.Cookies [FormsAuthentication.FormsCookieName]        如果(decryptedCookie!= NULL)
        {
            的FormsAuthenticationTicket票=
                FormsAuthentication.Decrypt(decryptedCookie.Value);            字符串[] =角色ticket.UserData.Split(新[] {,},
                 StringSplitOptions.RemoveEmptyEntries);            VAR身份=新的GenericIdentity(ticket.Name);
            VAR本金=新的GenericPrincipal(身份,角色);            HttpContext.Current.User =本金;
            = Thread.CurrentPrincipal中HttpContext.Current.User;
        }
    }
}

用法

 公共部分类_Default:页
{
    保护无效的Page_Load(对象发件人,EventArgs的发送)
    {
        如果(User.Identity.IsAuthenticated)
        {
            字符串的用户名= User.Identity.Name;            布尔isAdministrator = User.IsInRole(管理员);
        }
    }
}

I am trying to authenticate users who are logging into my web application from a log-in page. I was using this tutorial as a guide, which pretty much explained exactly what I'm hoping to do, but when I enter in the username and password, the validation is not working. Allow me to explain.

Here are relevant parts of my HTML. Nothing out of the ordinary:

<form id="form1" runat="server">
<div class=row>
<div class=col-xs-4>
    <div class="form-group">
<input id="txtUserName" type="text" runat="server">
<ASP:RequiredFieldValidator ControlToValidate="txtUserName"
       Display="Static" ErrorMessage="*" runat="server" 
       ID="vUserName" />
</div>
</div>

</div>
<div class=row>
<div class=col-xs-4>
<div class="form-group">
        <input id="txtUserPass" type="password" runat="server">
<ASP:RequiredFieldValidator ControlToValidate="txtUserPass"
      Display="Static" ErrorMessage="*" runat="server" 
      ID="vUserPass" />
</div>
</div>
</div>
<p><asp:Label ID="lblMsg" ForeColor="Red" runat="server" /></p>
<input type="submit" Value="Logon" runat="server" ID="cmdLogin"><p></p>
<ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" />
</form>

The page contains a username and a button to login (and a checkbox for remembering cookies but I don't think that's relevant to my problem).

Here is the code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Security;

namespace MRAApplication
{
    public partial class _1__0__0__0_LoginScreen : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick);
        }

        private bool ValidateUser(string userName, string passWord)
        {
            SqlConnection conn;
            SqlCommand cmd;
            string lookupPassword = null;

            // Check for invalid userName.
            // userName must not be null and must be between 1 and 15 characters.
            if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
                return false;
            }

            // Check for invalid passWord.
            // passWord must not be null and must be between 1 and 25 characters.
            if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
                return false;
            }

            try
            {
                // Consult with your SQL Server administrator for an appropriate connection
                // string to use to connect to your local SQL Server.
                conn = new SqlConnection("databaseConnect");
                conn.Open();

                // Create SqlCommand to select pwd field from users table given supplied userName.
                cmd = new SqlCommand("Select Password from Users where User=@userName", conn);
                cmd.Parameters.Add("@userName", System.Data.SqlDbType.VarChar, 25);
                cmd.Parameters["@userName"].Value = userName;

                // Execute command and fetch pwd field into lookupPassword string.
                lookupPassword = (string)cmd.ExecuteScalar();

                // Cleanup command and connection objects.
                cmd.Dispose();
                conn.Dispose();
            }
            catch (Exception ex)
            {
                // Add error handling here for debugging.
                // This error message should not be sent back to the caller.
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
            }

            // If no password found, return false.
            if (null == lookupPassword)
            {
                // You could write failed login attempts here to event log for additional security.
                return false;
            }

            // Compare lookupPassword and input passWord, using a case-sensitive comparison.
            return (0 == string.Compare(lookupPassword, passWord, false));

        }

        private void cmdLogin_ServerClick(object sender, System.EventArgs e)
        {
            if (ValidateUser(txtUserName.Value, txtUserPass.Value))
            {
                FormsAuthenticationTicket tkt;
                string cookiestr;
                HttpCookie ck;
                tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
          DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
                cookiestr = FormsAuthentication.Encrypt(tkt);
                ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                if (chkPersistCookie.Checked)
                    ck.Expires = tkt.Expiration;
                ck.Path = FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(ck);

                string strRedirect;
                strRedirect = Request["ReturnUrl"];
                if (strRedirect == null)
                    strRedirect = "default.aspx";
                Response.Redirect(strRedirect, true);
            }
            else
                Response.Redirect("1.0.0.0_LoginScreen.aspx", true);
        }
     }
    }

Now, I've tested my connection string and it works. It's connecting to a table in a SQL Server database which contains 3 columns of User, Password, and UserRole. Right now I just have a single test entry in the table, as shown here.

However, when I run the application and enter "test" into "txtUserName" and "password" into "txtUserPass" and click "submit" it is redirecting back to the login page, which means it is returning false for "if (ValidateUser(txtUserName.Value, txtUserPass.Value))".

If anybody could help me with this error I would appreciate it. Thank you for your help. :)

解决方案

this is my first time trying to do authentication so I'm not totally sure how to get the return value by using the breakpoint.

You want to test with hard-coded username and password before connecting to SQL server.

protected void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
    if (String.Equals(txtUserName.Value, "johndoe", 
        StringComparison.InvariantCultureIgnoreCase) &&
        String.Equals(txtUserPass.Value, "123456", 
        StringComparison.InvariantCultureIgnoreCase))
    {
        var roles = new[] {"Administrators"};

        var ticket = new FormsAuthenticationTicket(1, 
            txtUserName.Value,
            DateTime.Now,
            DateTime.Now.AddMinutes(30), 
            chkPersistCookie.Checked,
            string.Join(",", roles),
            FormsAuthentication.FormsCookiePath);

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
            FormsAuthentication.Encrypt(ticket));

        if (chkPersistCookie.Checked)
            cookie.Expires = ticket.Expiration;

        Response.Cookies.Add(cookie);

        string returnUrl = Request["ReturnUrl"];
        if (returnUrl == null)
            returnUrl = "default.aspx";
        Response.Redirect(returnUrl, true);
    }
    else
        Response.Redirect("1.0.0.0_LoginScreen.aspx", true);
}

How to create Principal Object

When an authenticated user is requested a page, you need to retrieve auth ticket from cookie, and create a Principal object.

// Global.asax.cs
public class Global : HttpApplication
{
    void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (decryptedCookie != null)
        {
            FormsAuthenticationTicket ticket =
                FormsAuthentication.Decrypt(decryptedCookie.Value);

            string[] roles = ticket.UserData.Split(new[] {","}, 
                 StringSplitOptions.RemoveEmptyEntries);

            var identity = new GenericIdentity(ticket.Name);
            var principal = new GenericPrincipal(identity, roles);

            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal = HttpContext.Current.User;
        }
    }
}

Usage

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {    
        if (User.Identity.IsAuthenticated)
        {
            string username = User.Identity.Name;

            bool isAdministrator = User.IsInRole("Administrators");
        }
    }
}

这篇关于其在asp.net web应用与认证的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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