[转]后台页面访问权限:页面基类&内置票据认证 使用方法

本文转自:http://www.cnblogs.com/fishtreeyu/archive/2011/01/29/1947421.html

一般网站后台页面除了登录页面login.aspx未登录用户可访问外,其它页面必须登录用户才可访问,

当用户未登录时进入某个页面则自动判断并跳转到登录页面:

(如果login.aspx页面用到图片及Css、Js文件,那么也必须允许未登录用户可访问Images、Css、Js文件夹)

方法一:运用页面基类BasePage.cs

1、BasePage.cs代码:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
 * 创建人:余泳彬
 * 创建时间:2011-1-17 11:13:32
 * 说明:页面基类
 * 版权所有:余泳彬
 */
using System;
using System.Collections.Generic;
using System.Web;
 
namespace Common
{
    /// <summary>页面基类</summary>
    public class BasePage : System.Web.UI.Page
    {
 
        /// <summary>
        /// 应用程序路径 如:/YongbinWeb/ 或 /
        /// </summary>
        public string ApplicationPath
        {
            get
            {
                string path = HttpContext.Current.Request.ApplicationPath.ToString();
                if (path.Trim() != "/") // 判断路径是否为“/”
                {
                    path += "/";
                }
                return path;
            }
        }
 
 
        /// <summary>
        /// 重写页面预处理事件(在页面初始化开始时引发)
        /// 验证用户是否登录
        /// </summary>
        protected override void OnPreInit(EventArgs e)
        {
            //判断会员是否登录,若未登录则跳转到登陆页面
            if (Session["admin"] == null)
            {
                this.Response.Redirect(ApplicationPath + "/admin/login.aspx", true);
                return;
            }
            base.OnPreInit(e);
        }
 
    }
}

2、后台需设置权限的页面.aspx.cs代码(继承BasePage类即可):

1
2
3
4
5
6
7
public partial class admin_ad_edit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
     }
}

  

  方法二:运用.Net内置票据认证 

1、  在根目录建立一个全局应用程序类Global.asax文件,拷入一段代码: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            // .Net 内置票据认证代码
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)  // 验证过的一般用户才能进行角色验证 
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket tiecket = id.Ticket;  // 取得身份验证票 
                        string userData = tiecket.UserData;    // 从UserData中恢复role信息
                        string[] roles = userData.Split(',');       // 将角色数据转成字符串数组,得到相关的角色信息
                        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);  // 这样当前用户就拥有角色信息了
                    }
                }
            }
 
        }

2、  在web.config 文件中配置目录权限及登录页  

A、登录页,在system.web节点中

1
2
3
4
5
6
7
8
<!--
    票据认证配置:登陆页。
    通过 <authentication> 节可以配置 ASP.NET 用来
    识别进入用户的安全身份验证模式。
-->
<authentication mode="Forms">
    <forms name="mycook" loginUrl="Admin/login.aspx" protection="All" path="/"/>
</authentication>

注:其中 Admin/login.aspx为若未登录则跳转的目标页面,这里跳转到登陆页

B、配置目录权限,在system.web节点外面  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!--票据认证配置:目录访问权限-->
<location path="Admin">
    <system.web>
        <authorization>
            <allow roles="admin"/>   <!--允许指定admin角色用户可访问-->
            <deny users="*"/>          <!-- 禁止所有非指定访问用户的访问-->
        </authorization>
    </system.web>
</location>
<!--所有用户均可访问登录页面-->
<location path="Admin/login.aspx">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>
<!--所有用户均可访问skin文件夹(css,images文件)-->
<location path="Admin/skin">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>

3、  在登录页的登录事件中的登录成功后拷入一段代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//  登陆事件
protected void btnLogin_Click(object sender, ImageClickEventArgs e)
{
    string name = txtName.Text.Trim();  // 用户名
    string pwd = txtPassWord.Text.Trim();  // 密码
    if (name == "yongbin" && pwd == "123456")
    {
        // 登录成功,内置票据认证拷入代码
        HttpCookie cook;
        string strReturnURL;  // 登录成功后返回的URL
        string roles = "admin"; // 用户角色
        // 建立身份验证票对象
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1, name, DateTime.Now, DateTime.Now.AddMinutes(30), false, roles);
        cook = new HttpCookie("mycook");
        cook.Value = FormsAuthentication.Encrypt(ticket);
        Response.Cookies.Add(cook);
        strReturnURL = Request.Params["ReturnUrl"];
        if (strReturnURL != null)
        {
            Response.Redirect(strReturnURL);
        }
        else
        {
            Response.Redirect("Default.aspx");
        }
 
    }
}

注:其中的url参数ReturnUrl为未登录时浏览的页面,

比如,用户未登录便浏览Admin目录下的 link_list.aspx页面,那么就自动跳转到登陆页面login.aspx,

这时候地址栏显示的URL形式是:http://localhost:2017/Admin/login.aspx?ReturnUrl=%2fAdmin%2flink_list.aspx

如果登陆后,我们要取得登陆的用户名可以这样取得,如:litUserName.Text = User.Identity.Name;

到这里,.Net基本的票据验证就成功了! 

另外:如果我们的网站是有两个文件夹需要分别用到票据认证,那怎么办呢?

比如后台的页面Admin目录,以及前台的会员中心页面User目录,因为这两个目录所用的登录页面不一样,所以就不能用同一个票据认证了;

 可修改如下:

1、修改web.config文件

A、修改<authentication>节点:

1
2
3
4
5
6
<authentication mode="Forms">
    <!--后台Admin目录权限-->
    <!--<forms name="mycook" loginUrl="Admin/login.aspx" protection="All" path="/"/>-->
    <!--跳转到login_direct.aspx,在login_direct.aspx页面判断是从Admin目录还是User目录中的页面点进来的-->
    <forms name="mycook" loginUrl="login_direct.aspx" protection="All" path="/"/>
</authentication>

B、增加User目录权限控制:

1
2
3
4
5
6
7
8
9
<!--票据认证配置:前台User目录访问权限-->
<location path="User">
    <system.web>
        <authorization>
            <allow roles="user"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>

   

2、建立login_direct.aspx页面,用于判断用户是从Admin目录还是User目录中的页面点击进来的,并跳转到相应目录页面,

login_direct.aspx.cs代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
namespace Yongbin.Shop.Web
{
    public partial class login_direct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string strReturnURL = Request.Params["ReturnUrl"];
                if (strReturnURL != null && strReturnURL.Contains("Admin")) //Admin目录
                {
                    Response.Redirect("Admin/login.aspx?ReturnUrl="+strReturnURL);
                }
                else
                {
                    Response.Redirect("Index.aspx?ReturnUrl=" + strReturnURL);
                }
            }
        }
    }
}

注:如果URL中的ReturnUrl参数含有Admin说明是从后台的Admin目录中跳转过来的,否则是从前台的User目录跳转过来的,这里前台的登陆框放在首页,因此User目录页面自动跳转到首页

3、前台的登录功能代码和后台一样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 登陆
protected void lbtnLogin_Click(object sender, EventArgs e)
{
    string name = txtName.Text.Trim();
    string pwd = txtPwd.Text.Trim();
    if (name.Length == 0 || pwd.Length == 0)
    {
        Yongbin.Shop.Utility.WebHelper.Alert(this, "请填写用户名和密码");
        return;
    }
 
    bool b = new Yongbin.Shop.DAL.UserDAO().Login(name, pwd);
    if (b)
    {
        // 登录成功,内置票据认证拷入代码
        HttpCookie cook;
        string strReturnURL;  // 登录成功后返回的URL
        string roles = "user"; // 用户角色
        // 建立身份验证票对象
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1, name, DateTime.Now, DateTime.Now.AddMinutes(30), false, roles);
        cook = new HttpCookie("mycook");
        cook.Value = FormsAuthentication.Encrypt(ticket);
        Response.Cookies.Add(cook);
        strReturnURL = Request.Params["ReturnUrl"];
        if (strReturnURL != null && strReturnURL.Contains(".aspx"))
        {
            Response.Redirect(strReturnURL);
        }
        else
        {
            Response.Redirect("Index.aspx");
        }
 
    }
    else
    {
        Yongbin.Shop.Utility.WebHelper.Alert(this, "用户名或密码错误");
        return
    }
}
原文地址:https://www.cnblogs.com/freeliver54/p/5106203.html