如何在asp.net中的登录页面上设置安全性

时间:2014-06-16 05:01:02

标签: c# asp.net sql-server login

我有一个登录页面和一个欢迎页面。 我已在用户数据库中保存了用户详细信息。

工作正常,但问题是用户可以通过更改网页的网址转到欢迎页面而无需登录。 如何设置,无需登录用户就无法进入欢迎页面。

这是我的登录页面代码 -

Login.aspx.cs

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

public partial class Login : System.Web.UI.Page
{
    string con_string = ConfigurationManager.ConnectionStrings["testAzharConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click1(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(con_string);
        string query = ("select count(*) from UserProfile where UserId ='" + txtUserId.Text + "' and Password='" + txtPassword.Text + "'");
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Connection = con;
        con.Open();
        int u = Convert.ToInt32(cmd.ExecuteScalar());
        con.Close();
        Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
        if (u > 0 && Captcha1.UserValidated)
        {
            Response.Cookies["txtUserName"].Value = txtUserId.Text;
            Response.Redirect("Main.aspx");
        }
        else if (u == 0)
        {
            lblCaptcha.Text = "Unauthorized User";
            txtCaptcha.Text = "";
            txtUserId.Text = "";
            txtPassword.Text = "";
        }
        else
        {
            lblCaptcha.ForeColor = System.Drawing.Color.Red;
            lblCaptcha.Text = "You have Entered InValid Captcha Characters please Enter again";
            txtCaptcha.Text = "";
        }
    }
}

的Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="rsv" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Login</title>
    <link rel="Stylesheet" href="StyleSheet.css" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <h1>Expense Management</h1>
    <h3>Please Login to manage Company Expenses.</h3>
    <table align="center" border="2" width="300">
        <tr>
            <td>User Id:</td>
            <td><asp:TextBox ID="txtUserId" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><asp:TextBox ID="txtPassword" TextMode="Password" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td colspan="2">
                <rsv:CaptchaControl ID="Captcha1" runat="server" CaptchaLength="5"
                CaptchaHeight="60" CaptchaMinTimeout="5" CaptchaMaxTimeout="200"
                ForeColor="#00FFCC" BackColor="White" CaptchaChars="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
                FontColor="Red" Width="177px"/>
            </td>
        </tr>
        <tr>
            <td>Enter Captcha:</td>
            <td><asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td><asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click1" /></td>
            <td><asp:Label ID="lblCaptcha" runat="Server" ForeColor="Red"></asp:Label></td>
        </tr>
        <tr>
            <td>
            <asp:HyperLink ID="linkForgetPassword" runat="server" ForeColor="Red" NavigateUrl="~/ForgetPassword.aspx">Forget Password ?</asp:HyperLink></td>
        </tr>
    </table>
    </form>
</body>
</html>

请告诉我如何在登录页面设置安全性。

3 个答案:

答案 0 :(得分:2)

这是一种做自己登录页面的方法

(您可能需要在以下方法中更改某些代码,但它可以让您了解如何在没有asp.net登录控制的情况下完成此操作)

1.使用web.config设置表单身份验证,如下所示:

 <authentication mode="Forms">
    <forms name="MYCOOKIE" loginUrl="Login.aspx" protection="All" 
         path="/" timeout="30">
      <credentials passwordFormat="MD5" />
    </forms>
  </authentication>

2.然后将authenticnticaeRequest方法设置为Global.asax.cs,如下所示:

    void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    FormsIdentity formID =  
                         (FormsIdentity)HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket ticket = formID.Ticket;

                    //get stored user data, in this case "user role"
                    string[] roles = new string[1] { ticket.UserData };
                    HttpContext.Current.User = new GenericPrincipal(formID, roles);
                }
            }
        }
    }

3.你需要一个课程来设置你的cookie使用这个;

    public class CookieMaker
    {

    public CookieMaker()
    {

    }

    public HttpCookie CreateCookie(bool remembered, string user, string role)
    {
        DateTime dtExpire;
        bool persistent = false;

        if (remembered)
        {
            dtExpire = DateTime.Now.AddDays(14);
            persistent = true;
        }
        else
        {
            dtExpire = DateTime.Now.AddMinutes(30);
        }

        FormsAuthenticationTicket frmTicket =
            new FormsAuthenticationTicket(1,
                                        user,
                                        DateTime.Now,
                                        dtExpire,
                                        persistent,
                                        role,
                                        FormsAuthentication.FormsCookiePath);

        //encrypt the created ticket.
        string encryptTicket = FormsAuthentication.Encrypt(frmTicket);

        //create a new cookie using encripted ticket
        HttpCookie cookie = new HttpCookie(
                   FormsAuthentication.FormsCookieName, encryptTicket);

        //set date for cookie expiration if check-box has checked.
        if (frmTicket.IsPersistent)
            cookie.Expires = frmTicket.Expiration;

        return cookie;
    }
 }

4.在您的登录点击按钮检查您的用户名和密码, 并为该特定用户设置角色,如下所示:

protected void BtnLogin_Click(object sender, EventArgs e)
{
     try
        {
            string returnURL;
            HttpCookie mycookie;

            //set a role to the user if it's authenticated
            string role = GetRole(txtUserId.Text, txtPassword.Text); 
            if (role != string.Empty)
            {
                CookieMaker cookie = new CookieMaker();
                mycookie = cookie.CreateCookie(chkRemember.Checked, 
                                               txtUserId.Text, role);
            }

            if (cookie != null)
            {
                Response.Cookies.Add(cookie);
                Response.Redirect("Main.aspx");
            }
            else
                lblError.Text = "Invalid username or password.";
        }
        catch (Exception ex) { lblError.Text = ex.Message; }
}

    public string GetRole(string userID, string pass)
    {
        string role = string.Empty;

            sqlCmd.Connection = sqlCnn;
            sqlCnn.Open();

            sqlCmd.CommandText = @"SELECT COUNT([UserId]) from UserProfile 
                                          WHERE [UserId] = @username AND 
                                               [Password] = @password";
            sqlCmd.Parameters.AddWithValue("@username", userID);
            sqlCmd.Parameters.AddWithValue("@password", pass);

            if (Convert.ToInt32(sqlCmd.ExecuteScalar()) > 0)
                role = "Member";

            return role;
    }

现在,您可以设置基页类以在页面加载之前检查其余页面:

public class MemberPageBase : System.Web.UI.Page
{

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!Context.User.Identity.IsAuthenticated)
        {
            this.RedirectToLogin();
        }
    }

    protected void RedirectToLogin()
    {
        Response.Redirect("~/Login.aspx");
    }
}

}

其余页面只是继承了上面的代码,如下所示:

public partial class Page1 : MemberPageBase 
{
    //....
}

因此,每当用户试图直接将网址放入页面时,如果未经过身份验证,则会将其重定向到登录页面。

答案 1 :(得分:1)

听起来您没有配置会员资格或角色。您应该浏览ASP.NET站点上的教程:Security Tutorials

答案 2 :(得分:1)

C#代码:(设置会话)

 protected void BtnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(con_string);
        string query = ("select count(*) from UserProfile where UserId ='" + txtUserId.Text + "' and Password='" + txtPassword.Text + "'");
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Connection = con;
        con.Open();
        int u = Convert.ToInt32(cmd.ExecuteScalar());
        con.Close();
        Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
        if (u > 0 && Captcha1.UserValidated)
        {
            // Adding Session to your page
            Session["user"] = txtUserId.Text;

            Response.Cookies["txtUserName"].Value = txtUserId.Text;
            Response.Redirect("Main.aspx");
        }
        else if (u == 0)
        {
            lblCaptcha.Text = "Unauthorized User";
            txtCaptcha.Text = "";
            txtUserId.Text = "";
            txtPassword.Text = "";
        }
        else
        {
            lblCaptcha.ForeColor = System.Drawing.Color.Red;
            lblCaptcha.Text = "You have Entered InValid Captcha Characters please Enter again";
            txtCaptcha.Text = "";
        }

    }

在您想要限制访问的页面上,请在加载页面前进行检查:

protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if (Session["user"] != null)
            {
                // Checking this session on the page, on the page load event.
                if (Session["user"] != null)
                {
                    Response.Redirect("Home1.aspx");
                }
            }
            else
            {
                Response.Redirect("Login.aspx");
            }
        }
    }

最后,不要忘记在注销或全局文件中销毁会话。同时使用hashing to secure your password并进行比较。

相关问题