0

我有webapi行動,這是用customauthattribute授權進行裝飾。如果當前用戶具有viewcustomer權限,則此屬性會使用db在內部進行檢查。有沒有人知道更好的方式來處理它,而不是使用customattribute。可能會攔截某個地方的所有請求並運行他正試圖訪問的用戶/許可/資源的授權檢查:例如,客戶ID爲10的getcustomer。因此,如果用戶無權訪問,請參閱客戶ID 10,他應該獲得403狀態。替代方法來處理控制器操作授權,而不是使用customattribute

[CheckPermission(Process.CustomerManagment,Permissions.View)] 
public IHttpActionResult GetCustomer(int customerId) 
{ 
} 
+0

你可以添加一個全局過濾但這意味着代碼是完全分開從你的行動方式,所以可能有點混亂。 – DavidG

+0

有沒有其他的方式,而不是使用屬性或全局屬性? – krishna

回答

0

您可以在您的web api的配置中添加全局過濾器。

實際上在啓動類(startup.cs或webapi.config),你可以在httpconfiguration調用對象以下方法

 var config = new HttpConfiguration(); 
     config.Filters.Add(new MyAuthFilterAttribute()); 

通過這種方式,將是全球您所有的API調用。

您應該擴展IAuthenticationFilter接口。

看看這裏的文檔 webapi documentation

0

一種選擇是,以創建可全局應用過濾器。例如,像這樣的東西。是的,它是可怕的,但給你一個開始:

public class GlobalAuthoriseAttribute : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; 
     var actionName = filterContext.ActionDescriptor.ActionName; 

     switch (controllerName) 
     { 
      case "Home": 
       //All call to home controller are allowed 
       return; 
      case "Admin": 
       filterContext.Result = new HttpUnauthorizedResult(); 
       return; 
     } 
    } 
} 

現在你可以在App_Start\FilterConfig.cs文件添加到您的整個應用程序:

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new GlobalAuthoriseAttribute()); 
} 
相關問題