2013-07-01 57 views
2

我有內部的自定義AuthorizeAttribute這樣如何讓[授權]自定義AuthorizeAttribute

public class DevMode : AuthorizationFilterAttribute 
{ 
    public override void OnAuthorization(HttpActionContext actionContext) 
    { 
     if (myConditionToAuthorize) 
     { 
      // how to allow [Authorize] ? 
     } 
    } 
} 

的問題是,它是伴隨着[授權]標籤這樣使用:

[Authorize, DevMode] 
public class UserController : ApiController { ... } 

我需要允許[Authorize] == true裏面[DevMode]

或者最好把它們放在一個獨特的授權類裏面嗎?但後來我不知道檢查授權數據。

回答

5

或者最好把它們放在一個獨特的授權類裏面嗎?

哦,是的,那的確會更好。你可以簡單地從AuthorizeAttribute派生並調用基方法:

public class DevModeAttribute : AuthorizeAttribute 
{ 
    protected override bool IsAuthorized(HttpActionContext actionContext) 
    { 
     var authorize = base.IsAuthorized(actionContext); 
     if (!authorized) 
     { 
      // the user is not authorized, no need to go any further 
      return false; 
     } 

     // now apply your custom authorization logic here and return true or false 
     ... 
    } 
} 

然後:

[DevMode] 
public class UserController : ApiController { ... } 
+0

「AuthorizeAttribute」中沒有'IsAuthorized'方法,'ApiController'中''AuthorizeAttribute'沒有被調用..只有'AuthorizationFilterAttribute'是。 (我使用框架4.5)。仔細看一下我的示例。 – Fabricio

+0

'AuthorizeAttribute'中沒有IsAuthorized方法:你確定嗎,仔細看一下這個文檔:http://msdn.microsoft.com/en-us/library/system.web.http.authorizeattribute.isauthorized (v = vs.108).aspx –

+0

'System.Web.Mvc.AuthorizeAttribute'和'System.Web.Http.AuthorizeAttribute'之間有很大的區別。我希望你使用後者作爲第一個顯然不是在API控制器中調用。另外,如果您使用的是ASP.NET Web API,那麼爲什麼用'asp.net-mvc'而不是用'asp.net-web-api'來標記問題標記?我會更新它來解決這兩種可能會使讀者迷惑的技術之間的誤解。 –

0

我用這個用這種方法

public class IsAdminAttribute : AuthorizeAttribute 
{ 
    protected override bool IsAuthorized(HttpActionContext actionContext) 
    { 
     IPrincipal principal = actionContext.RequestContext.Principal; 
     return principal.IsAdmin(); 
    } 
} 
添加自定義IsAdmin(基於索賠)

這種回答我自己的最後評論,所以希望它可以幫助別人請注意.IsAdmin是在IPrincipal檢查索賠的擴展方法。