覆盖MVC 4中的AuthorizeAttribute

时间:2013-10-14 11:05:25

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

在我的应用程序中,我想重定向授权用户以更新其个人资料页面,直到他们提供了所需信息。如果他们更新了个人资料,那么数据库中的IsProfileCompleted将设置为“true”。

所以,我知道这可以通过将检查条件放在控制器所需的操作中来完成。 但我希望通过自定义AuthorizeAttribute来实现此目的。

我用谷歌搜索和'StackOverflowed'获取信息,但感到困惑。请指导我。

2 个答案:

答案 0 :(得分:37)

public class MyAuthorizeAttribute: AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            // The user is not authorized => no need to go any further
            return false;
        }

        // We have an authenticated user, let's get his username
        string authenticatedUser = httpContext.User.Identity.Name;

        // and check if he has completed his profile
        if (!this.IsProfileCompleted(authenticatedUser))
        {
            // we store some key into the current HttpContext so that 
            // the HandleUnauthorizedRequest method would know whether it
            // should redirect to the Login or CompleteProfile page
            httpContext.Items["redirectToCompleteProfile"] = true;
            return false;
        }

        return true;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Items.Contains("redirectToCompleteProfile"))
        {
            var routeValues = new RouteValueDictionary(new
            {
                controller = "someController",
                action = "someAction",
            });
            filterContext.Result = new RedirectToRouteResult(routeValues);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }

    private bool IsProfileCompleted(string user)
    {
        // You know what to do here => go hit your database to verify if the
        // current user has already completed his profile by checking
        // the corresponding field
        throw new NotImplementedException();
    }
}

然后您可以使用此自定义属性修饰控制器操作:

[MyAuthorize]
public ActionResult FooBar()
{
    ...
}

答案 1 :(得分:0)

我已经使用了这段代码并添加了一些我自己的更改,即检查当前登录的用户是否在服务器上有会话状态,它们并不像以前那么昂贵!

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized && !Membership.isAuthenticated())
        {
            // The user is not authorized => no need to go any further
            return false;
        }

        return true;
    }
}
public class Membership
{
    public static SystemUserDTO GetCurrentUser()
    {
        // create a system user instance
        SystemUserDTO user = null;

        try
        {
            user = (SystemUserDTO)HttpContext.Current.Session["CurrentUser"];
        }
        catch (Exception ex)
        {
            // stores message into an event log
            Utilities.Log(ex.Message, System.Diagnostics.EventLogEntryType.Warning);

        }
        return user;
    }

    public static bool isAuthenticated()
    {
        bool loggedIn = HttpContext.Current.User.Identity.IsAuthenticated;
        bool hasSession = (GetCurrentUser() != null);
        return (loggedIn && hasSession);
    }
}