授权检查属性

时间:2013-08-25 17:17:30

标签: asp.net-mvc-4

我想通过检查正确的属性来实现重定向未授权用户。为此,我使用没有参数的构造函数创建一个class属性。

[AttributeUsage(AttributeTargets.Method)]
public class LoggedAttribute:Attribute
{
    public LoggedAttribute()
    {
        //TODO
    }
}

现在将此属性分配给需要授权的所有操作方法。

    [Logged]
    public ViewResult SendMessage()
    {
        return View();
    }

我有一个带有布尔标志IsLoggedIn的User模型。如何在发出标志的情况下,如何在class属性中检查此标志以将用户重定向到身份验证页面?

1 个答案:

答案 0 :(得分:1)

如果使用如下所示的自定义授权属性:

 public class AuthorizeUserAttribute : AuthorizeAttribute
 {    
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            //anything else you'd like to do like log it
            return false;
        }
    }
 }

然后您可以通过以下覆盖重定向它们:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    //disable the redirect
    if(disabled)
    {
        //do something else
    }else{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Account", 
                            action = "Login" 
                        })
                );
     }
}

更新:,您可以像这样使用它:

[AuthorizeUser]
public ActionResult myAction()
{
     return View();
}
相关问题