zoukankan      html  css  js  c++  java
  • MVC4验证用户登录特性实现方法

    在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性。

    // 摘要:
        //     表示一个特性,该特性用于限制调用方对操作方法的访问。
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
        public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter

    但是,美中不足的是,需要微软自带的一些用户验证的东西,比如数据库,配置等等的。

    常常我们只需要用SESSION或者Cookies去保存用户登录状态的时候,这岂不是杀鸡用牛刀的感觉?

    那么,我们按照微软官方的这个特性,重写一个属于自己的验证特性类就行了。下面是我常用的自己写的一段代码。

    复制代码
    using System.Web.Mvc;
    namespace System
    {
        /// <summary>
        /// 表示需要用户登录才可以使用的特性
        /// 如果不需要处理用户登录,则请指定AllowAnonymousAttribute属性
        /// </summary>
        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
        public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter
        {
    
            /// <summary>
            /// 默认构造函数
            /// </summary>
            public AuthorizationAttribute()
            {
                String authUrl = System.Configuration.ConfigurationManager.AppSettings["AuthUrl"];
                String saveKey = System.Configuration.ConfigurationManager.AppSettings["AuthSaveKey"];
                String saveType = System.Configuration.ConfigurationManager.AppSettings["AuthSaveType"];
                if (String.IsNullOrEmpty(authUrl))
                {
                    this._AuthUrl = "/waste/user/login";
                }
                else
                {
                    this._AuthUrl = authUrl;
                }
                if (String.IsNullOrEmpty(saveKey))
                {
                    this._AuthSaveKey = "LoginedUser";
                }
                else
                {
                    this._AuthSaveKey = saveKey;
                }
                if (String.IsNullOrEmpty(saveType))
                {
                    this._AuthSaveType = "Session";
                }
                else
                {
                    this._AuthSaveType = saveType;
                }
    
            }
    
            /// <summary>
            /// 构造函数重载
            /// </summary>
            /// <param name="authUrl">表示没有登录跳转的登录地址</param>
            public AuthorizationAttribute(String authUrl): this()
            {
                this._AuthUrl = authUrl;
            }
            /// <summary>
            /// 构造函数重载
            /// </summary>
            /// <param name="authUrl">表示没有登录跳转的登录地址</param>
            /// <param name="saveKey">表示登录用来保存登陆信息的键名</param>
            public AuthorizationAttribute(String authUrl,String saveKey):this(authUrl)
            {
                this.AuthSaveKey = saveKey;
                this.AuthSaveType = "Session";
            }
            /// <summary>
            /// 构造函数重载
            /// </summary>
            /// <param name="authUrl">表示没有登录跳转的登录地址</param>
            /// <param name="saveKey">表示登录用来保存登陆信息的键名</param>
            /// <param name="saveType">表示登录用来保存登陆信息的方式</param>
            public AuthorizationAttribute(String authUrl, String saveKey, String saveType)
                : this(authUrl, saveKey)
            {
                this._AuthSaveType = saveType;
            }
            /// <summary>
            /// 获取或者设置一个值,该值表示登录地址
            /// 如果web.config中末定义AuthUrl的值,则默认为:/waste/user/login
            /// </summary>
            private String _AuthUrl = String.Empty;
            public String AuthUrl
            {
                get { return _AuthUrl.Trim(); }
                set
                {
                    if (String.IsNullOrEmpty(value))
                    {
                        throw new ArgumentNullException("用于验证用户登录信息的登录地址不能为空!");
                    }
                    else
                    {
                        _AuthUrl = value.Trim();
                    }
                }
            }
            /// <summary>
            /// 获取或者设置一个值,该值表示登录用来保存登陆信息的键名
            /// 如果web.config中末定义AuthSaveKey的值,则默认为LoginedUser
            /// </summary>
            private String _AuthSaveKey = String.Empty;
            public String AuthSaveKey
            {
                get { return _AuthSaveKey.Trim(); }
                set
                {
                    if(String.IsNullOrEmpty(value))
                    {
                        throw new ArgumentNullException("用于保存登陆信息的键名不能为空!");
                    }
                    else
                    {
                        this._AuthSaveKey = value.Trim();
                    }
                }
            }
            /// <summary>
            /// 获取或者设置一个值,该值用来保存登录信息的方式
            /// 如果web.config中末定义AuthSaveType的值,则默认为Session保存
            /// </summary>
            private String _AuthSaveType = String.Empty;
            public String AuthSaveType
            {
                get { return _AuthSaveType.Trim().ToUpper(); }
                set
                {
                    if(String.IsNullOrEmpty(value))
                    {
                        throw new ArgumentNullException("用于保存登陆信息的方式不能为空,只能为【Cookie】或者【Session】!");
                    }
                    else
                    {
                        _AuthSaveType = value.Trim();
                    }
                }
            }
    
            public void OnAuthorization(AuthorizationContext filterContext)
            {
                if(filterContext.HttpContext==null)
                {
                    throw new Exception("此特性只适合于Web应用程序使用!");
                }
                else
                {
                    switch(AuthSaveType)
                    {
                        case "SESSION":
                            if (filterContext.HttpContext.Session == null)
                            {
                                throw new Exception("服务器Session不可用!");
                            }
                            else if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                            {
                                if (filterContext.HttpContext.Session[_AuthSaveKey] == null)
                                {
                                    filterContext.Result = new RedirectResult(_AuthUrl);
                                }
                            }
                            break;
                        case "COOKIE":
                            if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                            {
                                if (filterContext.HttpContext.Request.Cookies[_AuthSaveKey] == null)
                                {
                                    filterContext.Result = new RedirectResult(_AuthUrl);
                                }
                            }
                            break;
                        default:
                            throw new ArgumentNullException("用于保存登陆信息的方式不能为空,只能为【Cookie】或者【Session】!");
                    }
                }
            }
    
        }
    }
    复制代码

    然后在Web.Config文件里面加入下面几句用于配置登陆验证的一些信息:

     <appSettings>
        <add key="AuthUrl" value="/User/Login" />
        <add key="AuthSaveKey" value="LoginedUser" />
        <add key="AuthSaveType" value="Session" />
      </appSettings>

    使用实例:

    复制代码
    //...省略引用
    namespace MrHuo.Framework.Blog
    {
        [Authorization]//如果将此特性加在Controller上,那么访问这个Controller里面的方法都需要验证用户登录状态
        public class UserController:Controller
        {
            [AllowAnonymous]//这里是一个特例,有这个特性,表示这个方法不需要验证用户登录状态
            public ActionResult Index()
            {
                //...省略具体代码
            }
            //这里的方法需要验证登录状态,以下雷同
            public ActionResult Create()
            {
                //...省略具体代码
            }
        }
    }
    复制代码
  • 相关阅读:
    「网络流 24 题」太空飞行计划
    Wannafly挑战赛2D Delete (最短路好题)
    牛客 216 C 小K的疑惑
    Till I Collapse CodeForces
    bzoj 2734 集合悬殊 (状压dp)
    图写成一个类(2)
    写程序的易错点(不定期更新)
    强联通分量之kosaraju算法
    对各种lca算法的理解
    pb_ds的优先队列实现dijkstra
  • 原文地址:https://www.cnblogs.com/opop/p/5305538.html
Copyright © 2011-2022 走看看