Reputation: 2622
I have a complex application with lots of Web Api Calls which need permission checks that are within the database. An example simple api call I might have is:
[HttpGet]
public IEnumerable<StudentContact> GetStudentContacts(int id)
{
return db.StudentContacts.AsNoTracking().Where(n => n.StudentId == id && n.Current_Record == true).OrderBy(n => n.RankOrder);
}
And to do a permissions check I have to do the following:
int staffID = (User as CustomPrincipal).UserId;
int siteId = Functions.GetSiteIdFromCookie();
if (Functions.UserHasAccess(staffID, AccessLevels.access_StudentDetailsUpdate,siteId) == true) return true;
else return false;
What I would like to achieve is to create a custom authorization annotation so that I can have:
[HttpGet]
[PermissionAuth(AccessLevels.access_StudentDetailsUpdate,AccessLevels.access_StudentDetailsReadOnly)]
public IEnumerable......
And I may need to have an option of and/or i.e. both are true or one is true. Can anyone help?
Upvotes: 1
Views: 114
Reputation: 1187
This is possible by extending the AuthorizeAttribute
and overriding the IsAuthorized
method.
Something like the following is what you need.
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
};
}
}
Then above your method use [PermissionAuth(/*permissions here*/)]
Upvotes: 1