用session做个判断
买本书看看

解决方案 »

  1.   

    if(this.txtName.Text.ToString().Trim()=="")
    {
    Page.RegisterStartupScript("name","<script language='javascript'>document.Form1.all['txtName'].focus();alert('请输入用户名');</script>");
    return;
    }
    if(this.txtPass.Text.ToString().Trim()=="")

    {
    Page.RegisterStartupScript("name","<script language='javascript'>document.Form1.all['txtPass'].focus();alert('请输入用户密码');</script>");
    return;
    } string pass=sun.Encrypt(this.txtPass.Text.Trim().ToString()); string sql="select * from member where id='"+this.txtName.Text.ToString().Trim()+"' and pass='"+pass+"'";
    DataSet ds=sun.fill(sql);
    if(ds.Tables[0].Rows.Count==0)
    {
    Page.RegisterStartupScript("onclick","<script>window.alert('您输入的用户名和密码无法登陆,请与管理员联系');</script>");
    }
    else
    {
    Session["name"]=ds.Tables[0].Rows[0]["name"].ToString();
    Session["userid"]=ds.Tables[0].Rows[0]["id"].ToString();
                    if(ds.Tables[0].Rows[0]["manager"].ToString()=="1" && ds.Tables[0].Rows[0]["cando"].ToString()=="1")
    {
    Session["user"]="管理员";
    Response.Redirect("main_manager.aspx");
    }
    if(ds.Tables[0].Rows[0]["prof"].ToString()=="1" && ds.Tables[0].Rows[0]["cando"].ToString()=="1")
    {
    Session["user"]="财务专工";
    Response.Redirect("main_zhuangong.aspx"); }
    if(ds.Tables[0].Rows[0]["cando"].ToString()=="1")
    {
    Session["user"]="普通用户";
    Response.Redirect("default.aspx");
    }
    else
    {
    Page.RegisterStartupScript("onclick","<script>window.alert('您已经被管理员禁止使用此系统,请与管理员联系');</script>");

    }
      

  2.   

    刚刚是个验证页面,然后是在每个页面加上
    if(Session["userid"]==null)
    {
    Response.Write("<script language='javascript'>window.top.location.href='login.aspx';</script>");
    return;
    }就不能侵入了
      

  3.   

    以前用ASP,PHP,JSP编写网站代码的时候,站点安全性总是一件头疼的事情,虽然我们编写了用户登录,注册,验证页面,但是效果总是不理想。有时候我们不得不用大量的session变量来存放相关信息,处处设防。而在.NET环境下,这个问题处理起来就非常容易了。关键是要充分理解web.config文件。首先,介绍一下web.config文件。<?xml version="1.0" encoding="utf-8" ?>
    <configuration><system.web><!-- 动态调试编译
    设置 compilation debug="true" 以将调试符号(.pdb 信息)
    插入到编译页中。因为这将创建执行起来
    较慢的大文件,所以应该只在调试时将该值设置为 true,而所有其他时候都设置为
    false。有关更多信息,请参考有关
    调试 ASP.NET 文件的文档。
    -->
    <compilation defaultLanguage="vb" debug="true" /><!-- 自定义错误信息
    设置 customErrors mode="On" 或 "RemoteOnly" 以启用自定义错误信息,或设置为 "Off" 以禁用自定义错误信息。
    为每个要处理的错误添加 <error> 标记。
    -->
    <customErrors mode="RemoteOnly" /><!-- 身份验证 
    此节设置应用程序的身份验证策略。可能的模式是 “Windows”、
    “Forms”、“Passport”和 “None”
    -->
    <authentication mode="Windows" /> 
    <!-- 授权 
    此节设置应用程序的授权策略。可以允许或拒绝用户或角色访问
    应用程序资源。通配符:"*" 表示任何人,"?" 表示匿名 
    (未授权的)用户。
    -->
    <authorization>
    <allow users="*" /> <!-- 允许所有用户 --><!-- <allow users="[逗号分隔的用户列表]"
    roles="[逗号分隔的角色列表]"/>
    <deny users="[逗号分隔的用户列表]"
    roles="[逗号分隔的角色列表]"/>
    -->
    </authorization><!-- 应用程序级别跟踪记录
    应用程序级别跟踪在应用程序内为每一页启用跟踪日志输出。
    设置 trace enabled="true" 以启用应用程序跟踪记录。如果 pageOutput="true",则
    跟踪信息将显示在每一页的底部。否则,可以通过从 Web 应用程序
    根浏览 "trace.axd" 页来查看 
    应用程序跟踪日志。
    -->
    <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />
    <!-- 会话状态设置
    默认情况下,ASP.NET 使用 cookie 标识哪些请求属于特定的会话。
    如果 cookie 不可用,则可以通过将会话标识符添加到 URL 来跟踪会话。
    若要禁用 cookie,请设置 sessionState cookieless="true"。
    -->
    <sessionState 
    mode="InProc"
    stateConnectionString="tcpip=127.0.0.1:42424"
    sqlConnectionString="data source=127.0.0.1;user id=sa;password="
    cookieless="false" 
    timeout="20" 
    /><!-- 全球化
    此节设置应用程序的全球化设置。
    -->
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" /></system.web></configuration>好了,相信看过上面的介绍以后,对web.config文件一定非常了解了吧。下面我们就切入主题。为了防止用户没有经过验证就访问站点,我们的处理方法是当用户没有通过验证的时候点击任何页面将会直接跳到Login.aspx页面,具体代码如下:<authentication mode="Forms">
    <forms name="yourAuthCookie" loginUrl="login.aspx"
    protection="All" path="/" />
    </authentication>
    <authorization>
    <deny users="?" />
    </authorization>
    但是这样会产生一个问题,那就是如果我的站点有一些信息是可以让任意用户随意访问的,比如站点简介,使用说明等。如果按照上面的处理方法岂不让用户觉得很麻烦,呵呵,不急,在ASP.NET中自然有相应的解决办法。下面的代码可以实现匿名用户访问Test.aspx页面:<location path="test.aspx">
    <system.web>
    <authorization>
    <allow users="?" />
    </authorization>
    </system.web>
    </location>解决了上面两个问题,相信大家心里一定有底了吧。下面就开始实现login.aspx页面。利用C#和SQL Server2000,创建一个webform页面,加入相应的控件。具体代码如下:<%@ Page language="c#" Codebehind="login.aspx.cs"
    AutoEventWireup="false" Inherits="secure.login" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    <title>Secure Site</title>
    <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
    <meta content="C#" name="CODE_LANGUAGE">
    <meta content="JavaScript" name="vs_defaultClientScript">
    <meta content="http://schemas.microsoft.com/intellisense/ie5"
    name="vs_targetSchema">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    <form id="login" method="post" runat="server">
    <table cellSpacing="0" cellPadding="0" border="0">
    <tr>
    <td vAlign="top" align="left">
    <asp:label id="Message" Runat="server" ForeColor="#ff0000">
    </asp:label>
    </td>
    </tr>
    <tr>
    <td vAlign="top" align="left">
    <b>E-mail:</b>
    </td>
    </tr>
    <tr>
    <td vAlign="top" align="left">
    <asp:textbox id="username" Runat="server" Width="120">
    </asp:textbox>
    </td>
    </tr>
    <tr>
    <td vAlign="top" align="left">
    <b>Password:</b>
    </td>
    </tr>
    <tr>
    <td vAlign="top" align="left">
    <asp:textbox id="password" Runat="server"
    Width="120" TextMode="Password">
    </asp:textbox>
    </td>
    </tr>
    <tr>
    <td vAlign="top" align="left">
    <asp:checkbox id="saveLogin" Runat="server"
    Text="<b>Save my login</b>">
    </asp:checkbox>
    </td>
    </tr>
    <tr>
    <td vAlign="top" align="right">
    <asp:imagebutton id="btnLogin" Runat="server"
    ImageUrl="/images/w2k/login/btnLogin.gif">
    </asp:imagebutton>
    </td>
    </tr>
    </table>
    </form>
    </body>
    </HTML>
      

  4.   

    界面做好之后,就开始编写提交按钮事件,首先需要注册该事件,代码如下:private void InitializeComponent()

    this.btnLogin.Click += new System.Web.UI.ImageClickEventHandler(this.btnLogin_Click);
    .
    .
    .
    }
    事件注册好之后,自然就是编写事件处理函数了:private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
    CCommonDB sql = new CCommonDB();
    string redirect = "";if((redirect = sql.AuthenticateUser(this.Session, this.Response,
    username.Text, password.Text, saveLogin.Checked)) != string.Empty)
    {
    // Redirect the user
    Response.Redirect(redirect);
    }
    else
    {
    Message.Text = "Login Failed!";
    }
    }
    读者看完上面的代码之后一定想问CCommonDB是哪里来的东东,这是我编写的一个类,用来处理用户登录信息的,如果成功则把相关信息写入session、Cookie和SQL数据库,同时跳到default.aspx页面。具体如下:CCommonDB.csnamespace secure.Components
    {
    public class CCommonDB : CSql
    {
    public CCommonDB() : base() { }public string AuthenticateUser(
    System.Web.SessionState.HttpSessionState objSession, // Session Variable
    System.Web.HttpResponse objResponse, // Response Variable
    string email, // Login
    string password, // Password
    bool bPersist // Persist login
    )
    {
    int nLoginID = 0;
    int nLoginType = 0;// Log the user in
    Login(email, password, ref nLoginID, ref nLoginType);if(nLoginID != 0) // Success
    {
    // Log the user in
    System.Web.Security.FormsAuthentication.SetAuthCookie(nLoginID.ToString(), bPersist);// Set the session varaibles 
    objSession["loginID"] = nLoginID.ToString();
    objSession["loginType"] = nLoginType.ToString();// Set cookie information incase they made it persistant
    System.Web.HttpCookie wrapperCookie = new System.Web.HttpCookie("wrapper");
    wrapperCookie.Value = objSession["wrapper"].ToString();
    wrapperCookie.Expires = DateTime.Now.AddDays(30);System.Web.HttpCookie lgnTypeCookie = new System.Web.HttpCookie("loginType");
    lgnTypeCookie.Value = objSession["loginType"].ToString();
    lgnTypeCookie.Expires = DateTime.Now.AddDays(30);// Add the cookie to the response
    objResponse.Cookies.Add(wrapperCookie);
    objResponse.Cookies.Add(lgnTypeCookie);return "/candidate/default.aspx";
    }
    case 1: // Admin Login
    {
    return "/admin/default.aspx";
    }
    case 2: // Reporting Login
    {
    return "/reports/default.aspx";
    }
    default:
    {
    return string.Empty;
    }
    }
    }
    else
    {
    return string.Empty;
    }
    }/// <summary>
    /// Verifies the login and password that were given
    /// </summary>
    /// <param name="email">the login</param>
    /// <param name="password">the password</param>
    /// <param name="nLoginID">returns the login id</param>
    /// <param name="nLoginType">returns the login type</param>
    public void Login(string email, string password, ref int nLoginID, ref int nLoginType)
    {
    ResetSql();DataSet ds = new DataSet();// Set our parameters
    SqlParameter paramLogin = new SqlParameter("@username", SqlDbType.VarChar, 100);
    paramLogin.Value = email;SqlParameter paramPassword = new SqlParameter("@password", SqlDbType.VarChar, 20);
    paramPassword.Value = password;
    Command.CommandType = CommandType.StoredProcedure;
    Command.CommandText = "glbl_Login";
    Command.Parameters.Add(paramLogin);
    Command.Parameters.Add(paramPassword);Adapter.TableMappings.Add("Table", "Login");
    Adapter.SelectCommand = Command;
    Adapter.Fill(ds);if(ds.Tables.Count != 0)
    {
    DataRow row = ds.Tables[0].Rows[0];// Get the login id and the login type
    nLoginID = Convert.ToInt32(row["Login_ID"].ToString());
    nLoginType = Convert.ToInt32(row["Login_Type"].ToString());
    }
    else
    {
    nLoginID = 0;
    nLoginType = 0;
    }
    }
    }abstract public class CSql
    {
    private SqlConnection sqlConnection; // Connection string
    private SqlCommand sqlCommand; // Command
    private SqlDataAdapter sqlDataAdapter; // Data Adapter 
    private DataSet sqlDataSet; // Data Setpublic CSql()
    {
    sqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
    sqlCommand = new SqlCommand();
    sqlDataAdapter = new SqlDataAdapter();
    sqlDataSet = new DataSet();sqlCommand.Connection = sqlConnection;
    }/// <summary>
    /// Access to our sql command
    /// </summary>
    protected SqlCommand Command
    {
    get { return sqlCommand; }
    }/// <summary>
    /// Access to our data adapter
    /// </summary>
    protected SqlDataAdapter Adapter
    {
    get { return sqlDataAdapter; }
    }/// <summary>
    /// Makes sure that everything is clear and ready for a new query
    /// </summary>
    protected void ResetSql()
    {
    if(sqlCommand != null)
    {
    sqlCommand = new SqlCommand();
    sqlCommand.Connection = sqlConnection;
    }
    if(sqlDataAdapter != null)
    sqlDataAdapter = new SqlDataAdapter();if(sqlDataSet != null)
    sqlDataSet = new DataSet();
    }/// <summary>
    /// Runs our command and returns the dataset
    /// </summary>
    /// <returns>the data set</returns>
    protected DataSet RunQuery()
    {
    sqlDataAdapter.SelectCommand = Command;sqlConnection.Open();
    sqlConnection.Close();sqlDataAdapter.Fill(sqlDataSet);return sqlDataSet;
    }
    }
    }
      

  5.   

    先应用using System.Web.Security;private void 登陆_Click(object sender, System.EventArgs e)
    {

    if ((TextBox1.Text=="zp") && (TextBox2.Text=="zp"))
    {
    FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,true);
    Response.Redirect("default.aspx");
    }
    else
    {
    lb3.Text="用户密码输入错误!";
    }

    }
    不过,你要现在web.config中的<customErrors 
        mode="RemoteOnly" 
        /> 
    下边加入
    <authentication mode="Forms">
    <forms name=".SimpleFormAuth" path="/" loginUrl="login.aspx" protection="All" timeout="30">

    </forms>
    </authentication>
    <authorization>
    <deny users="?" />
    </authorization>
      

  6.   

    还可以到这看看~http://www.sbtop.com/blog/more.asp?name=kingbird&id=558
      

  7.   

    private void button1_Click(object sender, System.EventArgs e)
    {
        if(this.textBox_YHM.Text.Trim()!="yhm" & this.textBox_MM.Text.Trim()!="mm")
        {
             this.label3.Text = "用户名和密码有误!";
        }
        else
        {
    Form2 a = new Form2();
    a.ShowDialog();
        }
    }
    这个是最简单的,只要你输入的用户名不是yhm,密码不是mm就进不去,是这个就能进入,并进入新的窗体,那个form2就是新的窗体,这个没有新用户什么注册,什么用户权限问题(是管理员还是普通用户),应该是你想要的最简单、基本的登陆框
      

  8.   


    private void Button_logo_Click(object sender, System.EventArgs e)
    {
    string strCmd="SELECT count(*) FROM information WHERE (UserName LIKE '"+TextBox1.Text+"')AND(pwd LIKE '"+TextBox2.Text+"')";

    OleDbCommand myCommand=new OleDbCommand(strCmd,Con);
    myCommand.Connection.Open();
    int flag=(int)myCommand.ExecuteScalar();
    myCommand.Connection.Close();
    Con.Close();
    if(flag>0)
    {
    Session["UserName"]=this.TextBox1.Text;
    this.Response.Redirect("main.aspx");
    }
    else
    {
    this.Label2.Text="对不起!你的用户名与密码不符,请重新输入";
    this.TextBox1.Text="";
    this.TextBox2.Text="";
    }
    }
      

  9.   

    上面的几位高手已经搞得很详细了,我只简单说一下。一般身份验证有好多种方法:
    一、技术上最简单的就是在登录时要求用户数据用户和口令(一般都存在数据库中),用户登录成功以后就将用户信息存在(SESSION或者COOKIE中)然后REDIRECT到指定的主页面,为了防止用户绕过登录而直接进入,需要在每个要求登录以后才能访问的路径中添加验证代码,查看SESSION 或者COOKIE,如果用户没有登录,直接REDIRECT到那个登录页。
    二、用FORMS验证,这个难度稍大,但是也并不复杂,而且不许呀每个页都加入验证代码。。你需要配置WEB.CONFIG (一般每个WEB应用都有一个)
    这个指定了用户登录页面为aa.aspx如果用户没有登录会自动到aa.aspx页
    <authentication mode="Forms"> 
             <forms name="liujincai" loginUrl="aa.aspx"></forms> 
       </authentication>这个指定禁止你名访问,就是没有经过验证的用户是不允许访问路径下的所有页面的(除了aa.aspx)
        <authorization>
            <deny users="?" /> 
        </authorization>但是如果你有几个页面是允许不登录可以访问的比如,用户注册的页面(你不会连用户注册都不允许吧),那么你就需要添加下面的配置代码,假设注册页面为Reg.aspx
     <location path="Reg.aspx">
       <system.web>
          <authorization>
             <allow users="*"/>
          </authorization>
       </system.web>
    </location>三、你还可以用windows验证 等等。但是我觉得前两种用的多。如果看不懂web.config配置,请查看msdn.  我觉得理论上合容易理解。
      

  10.   

    楼上的 kbkingbird(丁翊) 我把你的代码都看完了,但怎么也看不出你从哪里验证了从用户界面上输入的东东和数据库里的东东进行了比效.......
      

  11.   

    建议用FORMS验证 其实也是最简单的
    只需要在web.config里面加节就OK
    有配置文件我们就要好好的利用