10

我正在使用 ASP.NET MVC 4 Web 应用程序作为某些 WCF 服务的前端。所有用户登录/注销和会话控制都在后端完成。MVC 应用程序应该只存储一个带有会话 ID 的 cookie。我的客户端不允许使用表单身份验证,一切都必须自定义。

我在 web.config 中设置了以下内容:

  <system.web>
...
    <authentication mode="None" />
  </system.web>

  <system.webServer>
    <modules>
...
      <remove name="FormsAuthentication" />
...    
    </modules>
  </system.webServer>

我还有一个全局过滤器:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        // Force all actions to request auth. Only actions marked with [AllowAnonymous] will be allowed.
        filters.Add(new MyAuthorizeAttribute());
    }
}

在 Global.asax 中调用

   FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

我已经用 [AllowAnonymous] 标记了每个不需要授权的控制器和操作。

现在我必须实现 MyAuthorizeAttribute。我尝试了一些教程,但没有一个完全符合我的场景。

基本上,我必须为每个动作处理以下场景:

  1. 如果存在有效的 cookie,则应认为当前请求已授权(将不会检查任何角色,只有一种用户)。
  2. 如果没有 cookie,我应该覆盖默认的 MVC 处理程序(它尝试加载帐户/登录)并将用户重定向到主页/索引页面,并显示用户应该登录的消息。
  3. 如果 WCF 方法调用抛出 FaultException,而我们的自定义 SecurityFault 表示会话已过期(SecurityFault 有一个包含异常原因的自定义枚举字段),我应该销毁我的自定义会话 cookie 并再次将用户重定向到主页/索引页面用户应该登录的消息,因为他的最后一个会话已过期。对于所有其他 SecurityFaults,我可以让它们通过 - 我有一个全局错误处理程序。

据我了解,我需要重写 AuthorizeCore (检查我的 cookie 以查看会话是否存在并且仍然有效)和 HandleUnauthorizedRequest (将用户重定向到主页/索引而不是默认登录页面)。

对于重定向,我尝试过:

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {            
        base.HandleUnauthorizedRequest(filterContext);
        filterContext.Result = new RedirectResult("/Home/Index/NeedsLogin");
    }

这似乎可以很好地处理第二种情况(不过,我不确定那个基本调用 - 需要吗?)。

对于第一种情况,我需要实现 AuthorizeCore。我不确定,如何正确地做到这一点。我已经看到 AuthorizeAttribute 有一些用于处理缓存情况的代码,也许还有更多隐藏的功能,我不想破坏它。

对于第三种情况,我不确定 MyAuthorizeAttribute 是否能够处理它。AuthorizeAttribute 能否捕获 Action 内部发生的异常,或者我必须在全局错误处理程序中处理 SecurityFault.SessionExpired 情况?

4

3 回答 3

7

不完全确定我明白了,但是如果您创建一个继承自 System.Web.MVC.Authorize 属性的自定义授权过滤器,就像这样。

    public class CustomAuthorize : AuthorizeAttribute
    {
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (CookieIsValid(filterContext.Request.Cookies["cookieyouwant"])
        {
             filterContext.Result = new RedirectResult("DestUrl");
        }
        else
        {
            filterContext.Result = new RedirectResult("/Home/Index/NeedsLogin");
        }
    }
}

然后装饰你需要使用这个授权的方法会成功吗?

于 2012-10-01T21:49:43.373 回答
3

这是我现在的做法:

  public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool authorized = false;

            /// MVC 4 boilerplate code follows
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");

            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                          || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

            if (skipAuthorization)
            {
                return;
            }

            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
            {
                throw new InvalidOperationException(
                    "MyAuthorizeAttribute cannot be used within a child action caching block."
                );
            }
            // end of MVC code


            // custom code
            if (!AuthorizeCore(filterContext.HttpContext))
            {
                // if not authorized from some other Action call, let's try extracting user data from custom encrypted cookie
                var identity = MyEncryptedCookieHelper.GetFrontendIdentity(filterContext.HttpContext.Request);
                // identity might be null if cookie not received
                if (identity == null)
                {
                    filterContext.HttpContext.User = new GenericPrincipal(new GenericIdentity(""), null);
                }
                else
                {
                    authorized = true;
                    filterContext.HttpContext.User = new MyFrontendPrincipal(identity);
                }

                // make sure the Principal's are in sync - there might be situations when they are not!
                Thread.CurrentPrincipal = filterContext.HttpContext.User;
            }

            // MVC 4 boilerplate code follows
            if (authorized)
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.

                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                HandleUnauthorizedRequest(filterContext);
            }
            //end of MVC code
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            // check to make sure the user is authenticated as my custom identity
            var principal = httpContext.User as MyFrontendPrincipal;
            if (principal == null)
                return false;

            var identity = principal.Identity as MyFrontendIdentity;
            if (identity == null)
                return false;

            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {            
            // default MVC result was:
            // filterContext.Result = new HttpUnauthorizedResult();

            // but I redirect to index login page instead of kicking 401
            filterContext.Result = new RedirectResult("/Home/Index/NeedsLogin");
        }

        // MVC 4 boilerplate code follows
        private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
        {
            validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
        }

        // This method must be thread-safe since it is called by the caching module.
        protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            bool isAuthorized = AuthorizeCore(httpContext);
            return (isAuthorized) ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest;
        }
    } 

但是,它不能处理我的第三种情况,所以我将在全局错误处理程序中实现它。

于 2012-10-02T08:59:54.623 回答
3

关于您的第一个要求:

正如您已经发现的那样,OnAuthorization它处理了许多方面,包括缓存。
如果您只对自定义验证用户凭据的方式感兴趣,我建议您AuthorizeCore改用覆盖。例如:

public class ClientCookieAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        HttpCookie cookie = httpContext.Request.Cookies[_tokenCookieName];

        bool isAuthenticated = ValidateUserByCookie(cookie);

        return isAuthenticated;
    }

    private bool ValidateUserByCookie(HttpCookie cookie)
    {
        var result = false;
        // Perform validation
        // You could include httpContext as well, to check further information
        return result;
    }

    private static const string _tokenCookieName = "myCookieName";
}

您可能还想看看其他线程:

  1. SO - 自定义授权属性
  2. ASP.NET - 自定义 AuthorizationFilter 重定向问题
  3. 忍者日记
于 2013-03-13T20:14:36.523 回答