【ASP.NET】通过Web.config实现登录


前言

本文是通过authentication(认证访问者)authorization( 访问权限),来实现一个简单的判断用户账号密码是否正确。


抛出问题

需要2个账号,一个账号为admin ,密码:123
另外一个账号为guest ,密码:1234

不允许匿名用户,和账号为guest的登录


代码实现

在这里插入图片描述

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />

      <authentication mode="Forms">
        <!--loginUrl是认证失败去的页面 defaultUrl 是认证成功访问的页面   -->
        <forms loginUrl="Login.aspx" defaultUrl="/Admin/Admin.aspx" path="/" name=".ASPXAUTH">

          <credentials passwordFormat="Clear">
            <!--账号密码可以看见-->
            <user name="admin" password="123"/>
            <user name="guest" password="1234"/>
            <!--认证的用户账号密码-->
          </credentials>
        </forms>
      </authentication>
    
      
      <!--禁止没有认证的用户访问-->
      <authorization>
        <deny users="?"/>    <!--拒绝没有登录的匿名用户-->
        <deny users="guest"/>   <!--拒绝账户为guest的用户-->    
        <allow users="admin"/> <!--允许账户为admin的用户-->
      </authorization>

    </system.web>

</configuration>

? 是没登录的用户(匿名用户) * 是所有用户
deny 是拒绝什么样的用户访问
allow 是允许什么样的用户访问


后台的登录(aspx.cs)

using System.Web.Security


            if (FormsAuthentication.Authenticate(this.TextBox1.Text, this.TextBox2.Text))  //看看配置文件里面是否有认证用户
            {
    
    
                FormsAuthentication.RedirectFromLoginPage(this.TextBox1.Text, true);      //保存cookie 然后打开要去的地址
            }

这样一个 过时 的登录就完成了
感谢观看!

猜你喜欢

转载自blog.csdn.net/qq_46874327/article/details/117259420