1

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?

2
  • Have you looked at using a filter? Commented Jan 8, 2015 at 12:17
  • No is it easy to setup a custom filter? Will it deny access to the function? Commented Jan 8, 2015 at 12:20

1 Answer 1

1

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*/)]

Sign up to request clarification or add additional context in comments.

6 Comments

I'll have a crack at this. What do you suggest I do in the case of an OR? i.e. as long as one of two permissions were set.
essentially you just have to adust the logic if the IsAuthorized method returns true they are allowed in
In the code above how do I get the permissions entered in the annotation into the IsAuthorized method?
They will be in the _accessLevels variables
VStudio doesn't like the _accessLevels = feature line here as it does not exist in the context
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.