【问题标题】:Return 401 when ClaimsAuthorizationManager.CheckAccess returns false当 ClaimsAuthorizationManager.CheckAccess 返回 false 时返回 401
【发布时间】:2015-04-21 13:49:31
【问题描述】:

我正在使用自定义 ClaimsAuthorizationManager 在 Web API 2 项目中实现授权

为此,需要重写CheckAccess() 方法来决定是否应允许当前主体访问,并返回相应的布尔值。问题是返回false 会导致Exception 被抛出,最终结果为500 Internal Server Error,而期望的结果是401 Unauthorized(或者可能是403 Forbidden?)。

有没有办法覆盖声明验证失败的结果,使其返回“正确”的 HTTP 响应而不是包罗万象的 500?

【问题讨论】:

  • 能否在返回false之前添加授权context.ErrorResult?
  • 或者不是返回false,而是抛出一个UserNotAuthorizedException
  • 上下文不是 System.Web.Mvc.AuthorizationContext 而是 System.Security.Claims.AuthorizationContext 无权访问任何内容。这就是我考虑使用过滤器的原因,MVC 的 AuthorizationContext 将允许我做你所说的。抛出我自己的异常将类似于当前的行为,因为我必须在更远的地方处理该异常。
  • 也许您将授权与身份验证混淆了?您如何验证用户使用 Api 技术?在身份验证期间,您可以处理您的索赔业务,该业务可以返回您喜欢的任何状态代码。
  • 我正在使用 AuthenticationFilter 进行身份验证,以执行身份验证并设置主体,按照 this tutorial。授权只发生在稍后阶段,我正在尝试使用ClaimsPrincipalPermission 属性来实现这方面的事情。

标签: asp.net asp.net-web-api asp.net-web-api2 claims-based-identity


【解决方案1】:

基于这两篇文章:

Article 1

Article 2

你可以实现你自己的ExceptionFilterAttribute,像这样

public class SecurityExceptionFilterAttribute : System.Web.Http.Filters.ExceptionFilterAttribute 
{
    public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Exception is System.Security.SecurityException)
        {
            actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            return;
        }

        base.OnException(actionExecutedContext);
    }
}

然后在Global.asax 文件中添加这个过滤器到HttpConfiguration:

config.Filters.Add(new SecurityExceptionFilterAttribute());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-21
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    相关资源
    最近更新 更多