15

我有一个 CustomApiAuthorizeAttribute:

public class CustomApiAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext == null)
            throw new ArgumentNullException("actionContext");

        bool skipAuthorization = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() || 
            actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();

        if (skipAuthorization) return;

        var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (cookie != null)
        {
            var decCookie = FormsAuthentication.Decrypt(cookie.Value);

            if (decCookie != null)
            {
                if (!string.IsNullOrEmpty(decCookie.UserData))
                {
                    HttpContext.Current.User = new CustomPrinciple(new CustomIdentity(decCookie));
                    return;
                }
            }
        }

        HttpContext.Current.Items["RequestWasNotAuthorized"] = true;

        HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName) { Expires = DateTime.Now.AddDays(-1d) });

        HandleUnauthorizedRequest(actionContext);
    }
}

我有一个控制器:

[CustomApiAuthorize]
public class RacingController : CustomApiController
{
    [HttpGet]
    [AllowAnonymous]
    public Venues Venues()
    {
        var asr = Services.GetVenues(Token);
        if(!string.IsNullOrEmpty(Token))
            SetAuthTicket(asr.Token);
        return asr.Payload;
    }
 }

尝试调用此操作时,我不断收到 401 Unauthorized 错误。调试告诉我 authorizeattribute 没有检测到 [AllowAnonymous] 的存在,但我不明白为什么。

谁能看到我做错了什么?或者有任何想法是否有其他冲突?

4

1 回答 1

20

如果您查看 System.Web.Http.AuthorizeAttribute 的源代码,则会进行以下检查以查看是否应跳过授权:

public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext == null)
        {
            throw Error.ArgumentNull("actionContext");
        }

        if (SkipAuthorization(actionContext))
        {
            return;
        }

        if (!IsAuthorized(actionContext))
        {
            HandleUnauthorizedRequest(actionContext);
        }
    }

        private static bool SkipAuthorization(HttpActionContext actionContext)
    {
        Contract.Assert(actionContext != null);

        return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
               || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
    }

所以我所做的是在我的自定义授权属性中实施类似的检查。

于 2014-04-21T10:01:22.767 回答