asp.net mvc5 身份验证过滤器


      文章,主要介绍如何在 asp.net mvc5  中如何运用新的 Authentication Filters 基于过滤器的验证机制。

      如果你在之前在项目中使用过MVC,你一定非常喜欢通过Authorization属性来为你的网站加强基于角色的安全验证的方式。在asp.net mvc 中开发人员可以进行身份验证,通过过滤器,它可以提供使用各种第三方供应商或自定义的身份验证机制进行身份验证的能力。

  

     注:Authentication的验证级别高于任何的Authorization验证。


     单运用于整个项目的Controller 或者某个Controller 的时候,Authentication filters 验证器比Authorization filters更加的优秀。现在先来创建一个 C# 的Asp.net 项目,用Authentication filters 来做一个项目。




        工程建好之后,我们来看看如何通过Authentication 过滤器实现简单的用户未登录返回登录界面功能. 首先在你的工程中建立CustomAttributes文件夹, 接下来在文件夹下面建立一个名字为CustomAttribute的类, 并且使它继承ActionFilterAttribute和IAuthenticationFilter:


        查看代码:

        public class BasicAuthAttribute: ActionFilterAttribute, IAuthenticationFilter

      

       IAuthenticationFilter接口定义了两个方法。OnAuthentication(AuthenticationContext filterContext) 和OnAuthenticationChallenge(AuthenticationChallengeContext  filterContext)。OnAuthentication方法首先被执行,并且可以包含任何所需要的验证。OnAuthenhentcationChallenge方法来限制已通过验证用户的行为。


     对于这个简单的例子,这里只实现OnAuthenticationChallenge方法. 留白OnAuthentication方法.



            public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext){

                          var user = filterContext.HttpContext.User; if (user == null || !user.Identity.IsAuthenticated) {

                         filterContext.Result = new HttpUnauthorizedResult();

                       }

}

     下面是完整的代码:


     

using System.Web.Mvc;
using System.Web.Mvc.Filters;
 
namespace VSMMvc5AuthFilterDemo.CustomAttributes
{
    public class BasicAuthAttribute : ActionFilterAttribute, IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
        }
 
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            var user = filterContext.HttpContext.User;
            if (user == null || !user.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}



        现在你可以在HomeController中使用并测试BasicAuthAttribute. 打开HomeController文件, 并且为它添加CustomAttributes命名空间的引用.



         

查看代码 
using VSMMvc5AuthFilterDemo.CustomAttributes;

然后应用自定义属性到HomeController:

[BasicAuthAttribute]
public class HomeController : Controller

现在当你编译并启动工程后, 应该会自动重定向到登陆页面:图3

ASP.NET MVC 5 Authentication Filters

图3:登录界面
(点击查看大图)


想要查看首页, 你需要注册一个用户账户:图4

ASP.NET MVC 5 Authentication Filters

图4:注册页面
(点击查看大图)

完成注册之后, 你将会自动重定向到首页:图5

ASP.NET MVC 5 Authentication Filters

图5:首页
(点击查看大图)

如你所见, 在MVC5中实现自定义的Authentication Filters并不是非常复杂. 目前这方面的文档非常少, 但是我可遇见到它能很好的应用在用户审核和日志记录方面, 或者使用自定义属性实现根据用户的认证提供商或身份标识提供给用户不同的访问权限的类似功能.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值