【问题标题】:Using a Custom Authentication/Authorization attribute for an action对操作使用自定义身份验证/授权属性
【发布时间】:2015-08-22 08:21:04
【问题描述】:

我们有一个使用 ASP 标识的网站,并且在所有适当的类上都带有 [Authorize] 属性,效果很好。

我想做的是为一组特定的操作创建一个单独的身份验证系统。这是一个不完全匿名的页面,但如果输入正确的 PIN 码即可查看。

我开始研究身份验证/授权属性,如果未通过身份验证,它会重定向到我的 PIN 输入页面。

所以我想我要问的是如何验证虚拟用户(又名:不在数据库中)以便在输入正确的 PIN 后能够访问这些页面?

【问题讨论】:

    标签: asp.net asp.net-mvc authentication asp.net-identity custom-attributes


    【解决方案1】:

    您可以通过从 AuthorizeAttribute 继承并覆盖 AuthorizeCore 方法来创建自己的版本。

    public class PinAuthorizeAttribute : AuthorizeAttribute
    {
        private readonly string _password;
    
        public PinAuthorizeAttribute(string password)
        {
            _password = password;
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //Check if user has entered the correct PIN, perhaps
            //by keeping the PIN in the Session
            if(Session["PIN") == _password)
                return true;
    
            return false;
        }
    }
    

    现在将其添加到您的操作方法中:

    [PinAuthorize("1234")]
    public ActionResult ProtectedIndex()
    { 
        //snip
    }
    

    【讨论】:

    • 注意我是从内存中输入这段代码的,但它应该可以正常工作!密码也是硬编码的,你可能想从数据库或配置文件中获取它。
    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2018-05-19
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多