为了创建身份验证过滤器,开发人员需要新建一个c#asp.net工程,并且从列出的工程类型中选择mvc。来自kunz,leigh&associates公司的高级软件开发工程师eric vogel已经测试了身份验证过滤器的用法。他创建了一个自定义过滤器,如果用户未通过身份验证,就将其重定向回登录页面。
eric创建了一个customattributes目录和一个新类customeattribute,该类继承了
actionfilterattribute和iauthenticationfilter: public class basicauthattribute: actionfilterattribute,iauthenticationfilter
接口iauthenticationfilter的onauthentication()方法可以用于执行任何需要的身份验证,而onauthenticationchallenge方法基于已验证用户的身份限制其访问。
onauthenticationchallenge方法接收authenticationchallengecontext参数,其实现代码如下所示:
public void onauthenticationchallenge(authenticationchallengecontext filtercontext) { var user = filtercontext.httpcontext.user; if (user == null || !user.identity.isauthenticated) { filtercontext.result = new httpunauthorizedresult(); } }
读者可以从eric的博文获得完整的源代码。basicauthattribute类很容易测试,打开homecontroller类文件,并添加下面的代码即可:
using vsmmvc5authfilterdemo.customattributes;
最后,将自定义属性应用到homecontroller类,如下所示:
[basicauthattribute] public class homecontroller : controller
