使用自定义身份验证/授权属性执行操作

时间:2015-06-07 23:21:10

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

我们有一个使用ASP身份的网站,并且适用于所有相应类别上的[Authorize]属性。

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

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

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

1 个答案:

答案 0 :(得分:2)

您可以通过继承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
}
相关问题