【原创】MVC2/MVC3 Forms身份验证简单控制
在一个小型MVC项目中用到了身份验证,权限固定有3个等级,普通用户、管理员、超级管理员;
之前在使用.aspx页面的时候,可以在Web.Config中配置<location></location>节点控制,但在MVC项目中,发现此配置失效了,不知道是什么原因,还是MVC已经不支持这种配置了,尚未查明原因。
一:在MVC中使用到的Forms身份验证控制基类是 AuthorizeAttribute,继承此基类并重写OnAuthorization方法即可,
1: /// <summary>
2: /// Forms身份验证
3: /// </summary>
4: public class ActionAuthorize : AuthorizeAttribute
5: {
6: Level level = Level.Normal;
7:
8: /// <summary>
9: /// 构造函数,传入页面安全等级
10: /// </summary>
11: /// <param name="level">页面安全等级</param>
12: public ActionAuthorize(Level _level = Level.Normal)
13: {
14: level = _level;
15: }
16:
17: public override void OnAuthorization(AuthorizationContext filterContext)
18: {
19: base.OnAuthorization(filterContext);
20: bool isAuth = true;
21: if (!HttpContext.Current.User.Identity.IsAuthenticated)
22: {
23: isAuth = false;
24: }
25: else
26: {
27: switch (level)
28: {
29: case Level.Admin:
30: if (IdentityCookie.Value.Level < (int)Level.Admin)
31: {
32: isAuth = false;
33: }
34: break;
35: case Level.SuperAdmin:
36: if (IdentityCookie.Value.Level < (int)Level.SuperAdmin)
37: {
38: isAuth = false;
39: }
40: break;
41: }
42: }
43: if (!isAuth)
44: {
45: HttpContext.Current.Response.Redirect("~/Home/LogOn");
46: HttpContext.Current.Response.End();
47: }
48: }
49: }
50:
51: public enum Level
52: {
53: Normal = 0,
54: Admin = 1,
55: SuperAdmin = 2
56: }
二:然后在Controller头上引用即可,当然也可以加到具体的某个Action上。
[ActionAuthorize(Level.Admin)] public class ManageController : Controller { }
完成以上两部,就可以实现MVC的Forms身份验证控制了.