使用 MVC 自定义授权过滤器验证不同区域

授权滤器执行你的授权策略,以确保动作方法只被已认证用户调用。授权过滤器实现 IAuthorizationFilter 接口

设置身份认证模式为 Form 模式

1
2
3
4
5
6
<system.web>
<!--身份认证模式-->
<authentication mode="Forms">
<forms timeout="2880"></forms>
</authentication>
</system.web>

登录代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public bool Login(string Account_Name, string Account_Password)
{
if(Account_Name == "Admin" && Account_Password == "Password") {

FormsAuthentication.SetAuthCookie(Account_Name, true);

Session["Account_Name"] = Account_Name;

return true;
}
else
{
return false
}
}

自定义授权过滤器

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class CustomAuthAttribute : AuthorizeAttribute
{
/// <summary>
/// 自定义授权检查
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// 检查关键 Session,如果关键 Session 丢失主动将登录失效,并设置一个名为 expired 的 Cookie 供前端检查
if (HttpContext.Current.Session["Account_Name"] == null)
{
HttpCookie httpCookie = new HttpCookie("expired", DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss.ffff"));

// 获取请求的区域
string area = httpContext.Request.RequestContext.RouteData.DataTokens.FirstOrDefault(m => m.Key == "area").Value?.ToString();

httpCookie.Path = "/" + area;

httpContext.Response.SetCookie(httpCookie);
return false;
}
else
{
httpContext.Response.SetCookie(new HttpCookie("expired", null));
}

// 获取登陆时设置的用户标识
string user = httpContext.User.Identity.Name;
// 检查用户标识
if (user == null || user == "")
{
return false;
}
else
{
return true;
}
}

/// <summary>
/// 处理未能授权的 HTTP 请求
/// </summary>
/// <param name="filterContext"></param>
/// <returns></returns>
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// 获取请求的区域
string area = filterContext.RouteData.DataTokens.FirstOrDefault(m => m.Key == "area").Value?.ToString();

// 根据不通的区域跳转到不通的登录页面

// 处理没有区域的情况
if (area == null || area == "")
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
{ "controller", "Login"},
{ "action", "Index"},
//{ "returnUrl", filterContext.HttpContext.Request.RawUrl}
});
}
else if (area == "Admin")
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
{ "area", area},
{ "controller", "Login"},
{ "action", "Index"},
//{ "returnUrl", filterContext.HttpContext.Request.RawUrl}
});
}
}
}

使用自定义授权过滤器

1
2
3
4
5
6
7
8
[CustomAuth]
public class HomeController
{
public ActionResult Index()
{
return View();
}
}