Asp.net-Mvc

AllowAnonymous 不使用自定義 AuthorizationAttribute

  • November 28, 2012

這讓我難倒了一段時間。顯然,常見的類似情況似乎都不適用於這裡。我可能錯過了一些明顯的東西,但我看不到它。

在我的 Mvc Web 應用程序中,我使用 Authorize 和 AllowAnonymous 屬性的方式是,您必須明確地將操作公開為公開可用,而不是鎖定站點的安全區域。我更喜歡這種方法。但是,我無法在我的 WebAPI 中獲得相同的行為。

我編寫了一個繼承自 System.Web.Http.AuthorizeAttribute 的自定義授權屬性,其內容如下:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class MyAuthorizationAttribute : System.Web.Http.AuthorizeAttribute

我已將此註冊為過濾器:

   public static void RegisterHttpFilters(HttpFilterCollection filters)
   {
       filters.Add(new MyAuthorizationAttribute());
   }

這一切都按預期工作,沒有憑據將不再可用。問題是現在以下方法將不允許 AllowAnonymous 屬性執行此操作:

[System.Web.Http.AllowAnonymous]
public class HomeController : ApiController
{
   [GET("/"), System.Web.Http.HttpGet]
   public Link[] Index()
   {
       return new Link[] 
       { 
           new SelfLink(Request.RequestUri.AbsoluteUri, "api-root"),
           new Link(LinkRelConstants.AuthorizationEndpoint, "OAuth/Authorize/", "authenticate"),
           new Link(LinkRelConstants.AuthorizationTokenEndpoint , "OAuth/Tokens/", "auth-token-endpoint")
       };
   }
}

最常見的情況似乎是混淆了兩個 Authorize / AllowAnonymous 屬性。System.Web.Mvc 用於 Web 應用程序,而 System.Web.Http 用於 WebAPI(無論如何我都理解)。

我使用的兩個屬性都來自同一個命名空間——System.Web.Http。我假設這只會繼承基本功能並允許我在 OnAuthotize 方法中註入我需要的程式碼。

根據文件, AllowAnonymous 屬性在我立即呼叫的 OnAuthorize 方法中起作用:

   public override void OnAuthorization(HttpActionContext actionContext)
   {
       base.OnAuthorization(actionContext);

任何想法將不勝感激。

有沒有人遇到過這個問題並找到了根本原因?

在 AuthorizeAttribute 中有以下程式碼:

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

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

將此方法包含在您的 AuthorizeAttribute 類中,然後將以下內容添加到 OnAuthorization 方法的頂部,以在找到任何 AllowAnonymous 屬性時跳過授權:

if (SkipAuthorization(actionContext)) return;

引用自:https://stackoverflow.com/questions/13595723