zoukankan      html  css  js  c++  java
  • ASP.NET MVC 5改进了基于过滤器的身份验证

    ASP.NET MVC 5包含在最近发布的Visual Studio 2013开发者预览版中,它使开发人员可以应用身份验证过滤器,它们提供了使用各种第三方供应商或自定义的身份验证提供程序进行用户身份验证的能力。不过,这些过滤器要在调用授权过滤器之前应用。

      为了创建身份验证过滤器,开发人员需要新建一个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

      英文原文:Improved Authentication with Filters in ASP.NET MVC 5

  • 相关阅读:
    #3146. 「APIO 2019」路灯
    #3145. 「APIO 2019」桥梁
    #3144. 「APIO 2019」奇怪装置
    雅礼集训2019 D7T2 Subsequence
    Luogu P3600 随机数生成器
    CF 704 D. Captain America
    Luogu P2570 [ZJOI2010]贪吃的老鼠
    Loj #2585. 「APIO2018」新家
    Access denied for user 'root'@'localhost' (using password: NO)
    MySql修改密码
  • 原文地址:https://www.cnblogs.com/Blog-Yang/p/3313842.html
Copyright © 2011-2022 走看看