2015-01-08 199 views
1

我有一個複雜的應用程序,其中包含許多Web Api調用,它們需要數據庫中的權限檢查。一個例子簡單的API調用我可能是:ASP.Net MVC Web API的自定義授權

[HttpGet] 
    public IEnumerable<StudentContact> GetStudentContacts(int id) 
    { 
     return db.StudentContacts.AsNoTracking().Where(n => n.StudentId == id && n.Current_Record == true).OrderBy(n => n.RankOrder); 
    } 

而要做到權限檢查我必須做到以下幾點:

int staffID = (User as CustomPrincipal).UserId; 
int siteId = Functions.GetSiteIdFromCookie(); 
if (Functions.UserHasAccess(staffID, AccessLevels.access_StudentDetailsUpdate,siteId) == true) return true; 
else return false; 

我想達成什麼是創建一個自定義授權註解所以我可以有:

[HttpGet] 
[PermissionAuth(AccessLevels.access_StudentDetailsUpdate,AccessLevels.access_StudentDetailsReadOnly)] 
public IEnumerable...... 

而我可能需要有一個選項和/或即兩者都是真實的或一個是真實的。誰能幫忙?

+0

你看着使用過濾器? – Liath

+0

不容易設置自定義過濾器嗎?它會拒絕訪問該功能嗎? – user1166905

回答

1

這可以通過擴展AuthorizeAttribute並覆蓋IsAuthorized方法來實現。 下面的東西就是你需要的東西。

public class PermissionAuthAttribute : AuthorizeAttribute 
{ 
    private readonly List<string> _accessLevels; 


    public PermissionAuth(params string[] accessLevels) 
    { 
     _accessLevels = accessLevels.ToList(); 
    } 

    protected override bool IsAuthorized(HttpActionContext actionContext) 
    { 
     if (!base.IsAuthorized(actionContext)) 
     { 
      return false; 
     } 
     int staffID = (User as CustomPrincipal).UserId; 
     int siteId = Functions.GetSiteIdFromCookie(); 
     if (Functions.UserHasAccess(staffID, AccessLevels.access_StudentDetailsUpdate,siteId) == true) { 
      return true; 
     } 
     else { 
      return false 
     }; 
    } 
} 

然後你的方法上面使用[PermissionAuth(/*permissions here*/)]

+0

我會對此有一個解釋。對於OR的情況,你建議我做什麼?即只要設置了兩個權限中的一個即可。 – user1166905

+0

基本上你只需要修改邏輯如果'IsAuthorized'方法返回true它們被允許在 –

+0

在上面的代碼中我如何獲得在註釋中輸入的權限到IsAuthorized方法中? – user1166905