且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MVC 4重写AuthorizeAttribute

更新时间:2023-02-26 08:36:28

 公共类MyAuthorizeAttribute:AuthorizeAttribute
{
    保护覆盖布尔AuthorizeCore(HttpContextBase的HttpContext)
    {
        VAR授权= base.AuthorizeCore(HttpContext的);
        如果(!授权)
        {
            //用户无权=>没有必要再往前走
            返回false;
        }        //我们有一个身份验证的用户,让我们自己的用户名
        字符串authenticatedUser = httpContext.User.Identity.Name;        //并检查他已经完成了他的个人资料
        如果(!this.IsProfileCompleted(authenticatedUser))
        {
            //我们存放一些密钥到当前HttpContext使
            //将HandleUnauthorizedRequest方法会知道它是否
            //应该重定向到登录或CompleteProfile页
            httpContext.Items [redirectToCompleteProfile] =真;
            返回false;
        }        返回true;
    }    保护覆盖无效HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        如果(filterContext.HttpContext.Items.Contains(redirectToCompleteProfile))
        {
            VAR routeValues​​ =新RouteValueDictionary(新
            {
                控制器=someController
                行动=someAction
            });
            filterContext.Result =新RedirectToRouteResult(routeValues​​);
        }
        其他
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }    私人布尔IsProfileCompleted(字符串用户)
    {
        //你知道这里做什么=>走打你的数据库,以验证是否
        //当前用户已经完成了他的个人资料通过检查
        //相应的字段
        抛出新NotImplementedException();
    }
}

,然后你可以装饰这个自定义属性你的控制器动作:

  [MyAuthorize]
公众的ActionResult FooBar的()
{
    ...
}

In my application, I want to redirect the authorized user to update their profile page until they have provided required information. If they update profile, then the IsProfileCompleted is set to 'true' in the database.

So, I knows that this can be done by putting check condition in required action of controller. But I want to do this by customizing the AuthorizeAttribute.

I Googled and '***ed' for information, but got confused. Please guide me.

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();
    }
}

and then you could decorate your controller actions with this custom attribute:

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