安全认证(Login画面的web.config)

来源:互联网 发布:尼古拉二世 知乎 编辑:程序博客网 时间:2024/05/18 01:35

<configuration>
    <configurations>
        <sectionGroup name="system.web">
            <section name="globalization"/>
            <section name="authentication"/>
            <section name="authorization"/>
        </sectionGroup>
    </configurations>

    <system.web>
        <globalization requireEncoding="GB2312" responseEncoding="GB2312"/>
        <authentication mode="Forms">
            <forms name="form1" loginurl="login.aspx" protection="All" timeout="30" path="/">
                <credentials passwordFormat="Clear">
                    <user name="allon" password="123456"/>
                    <user name="allonkwok" password="123456"/>
                </credentials>
            </forms>
        </authentication>

        <authorization>
            <deny users="Rita,?"/>
        </authorization>
    </system.web>
</configuration>
一、<authentication>
    <authentication>标记有一个mode属性,包含四种值:
    1.Forms
        asp.net网页将以窗体字段内容(通常是登陆帐号,密码,保存于cookie内)表示用户身份.
    2.None
        不进行认证过程,但是Win2000/NT本身的访问控制列表仍可能拒绝用户访问某个目录.
    3.Passport
        以微软的Passport web service来认证用户身份.
    4.Windows
        以Win2000/NT的机制来验证用户的身份,常见的有基础(Basic)、摘要式(Digest)、Kerberos等三种方式。

二、<Forms>
    1.name属性
        指定窗体验证的cookie名称,本例设置为 form1
    2.loginurl属性
        指定未通过认证的用户将被重定向的网页,本例是 login.aspx
    3.path属性
        设置cookie的访问路径.
    4.protection属性
        cookie数据的保护模式,有四种,分别是 All | None | Encryption | Validation
    5.timeout属性
        cookie有效周期,单位为秒,每一次发出request后会重新计算.

三、<credentials>
    Credentials代表认证的信息,此处我们仅加入一位用户用户及密码,并以明码(Clear)方式传送,<credentials>标记有一个属性,称做 passwordformat,其值可以为Clear | MD5 | SHA1

四、<user>
    <user>标记用来指定用户名称和密码,本例中只有两组:allon   以及 allonkwok
    在web.config中,用户名和密码并不是必备的,我们可以通过前述的<credential>节来指定保存认证信息的场所,可能是某个数据库或目录。

五、登陆检验程序
Public void Login_Check(object sender,EventArgs e)
{
    if (FormsAuthentication.Authenticate(txtUser.Text,txtPwd.Text))
    {
        FormsAuthentication.RedirectFromLoginPage(txtuser.Text,True);
    }
    else
    {
        lblShow.Text="登陆失败,请重新登陆";
    }
}本程序通过FormsAuthentication类(class)的Authenticate方法验证前台用户输入的帐号,密码,如果通过验证,再以RedirectFromLoginPage方法重定向到真正要显示的网页.
RedirectFromLoginPage()方法有两个参数,一个是帐号名称(txtUser),第二个是指定是否永久保存cookie

六、程序中判断是否已经被认证
    成功地认证某位用户之后,可用过 User 类,取出用户名和认证类型等,User.Identity 属性内含三个子属性
    1.IsAuthenticated
        此属性用来判断某位用户是否已通过验证,其值为true或false
    2.Name
        返回被验证后的名称,以本例为 textUser
    3.Type
        返回认证类型
Public Page_Load(object sender , EventArgs e)
{
    lblUser.Text=User.Identity.Name;
}

原创粉丝点击