且构网

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

ASP.NET MVC - 动态授权

更新时间:2023-02-14 16:55:56

如果你想利用授权过程的控制,你应该继承AuthorizeAttribute并重写AuthorizeCore方法。然后,只需用你的 CmsAuthorizeAttribute 而不是默认的装饰你的控制器。

If you want to take control of the authorization process, you should subclass AuthorizeAttribute and override the AuthorizeCore method. Then simply decorate your controllers with your CmsAuthorizeAttribute instead of the default.

public class CmsAuthorizeAttribute : AuthorizeAttribute
{
    public override virtual bool AuthorizeCore(HttpContextBase httpContext)
    {
        IPrincipal user = httpContext.User;
        IIdentity identity = user.Identity;

        if (!identity.IsAuthenticated) {
            return false;
        }

        bool isAuthorized = true;
        // TODO: perform custom authorization against the CMS


        return isAuthorized;
    }
}

这样做的缺点是,你将无法访问构造函数注入的IoC,所以你必须从容器直接请求任何依赖关系。

The downside to this is that you won't have access to ctor-injected IoC, so you'll have to request any dependencies from the container directly.