0

Good afternoon, everyone! I'm using repository pattern for access EDM, and I want develop some kind of rights check using custom attribute AccessByRole like this:

public abstract class RepositoryBase: IRepository
{
    ...
    [AccessByRole]
    public virtual void Add(T entity)
    {
        ....
    }
    [AccessByRole]
    public virtual void Update(T entity)
    {
        ...
    }
    [AccessByRole]
    public virtual void Delete(T entity)
    {
        ...
    }        
    [AccessByRole]
    public virtual T GetById(long id)
    {
        ...
    }        
}

Usage of repository (I'm using Autofac for IoC):

public class Service
{
   private readonly IRepository repository;
   public Service(IRepository repository)
   {
       this.repository = reporitory;
   }
   ....
   public UpdateUserEntities(...)
   {
   ...
      reporitory.Update(T); // There is a need for check user rights before calling this method.
   }

}

There is a necessity of checking rights of the User before calling CRUD operations. So my question is: How should the attributes source code look like, so the CRUD operations called after the rights checked?

  • You should check roles and right in services, not repository. Repository in general is just a useful interface to handling data requests. Services is used for your business logic, and checking rights is a part of it – Andrey Ischencko Jan 11 '16 at 16:33
  • Well, I disagree with your approach - in my opinion checking rights is closer to data layer rather than service layer. I found solution here: http://docs.autofac.org/en/latest/advanced/interceptors.html, in this case I just implemented interface IInterceptor – Dimich Parkhomchuk Jan 11 '16 at 20:32

1 Answers1

0

Well, the easiest way would be to check the role in each action, and short circuit if that's not authorized. For example:

 if(AuthorizedForRole[someAction]==true)
 {
     [some code]
 }else{
     Return "Unauthorized access attept";
 }
  • Michael, thnx for your answer! What exaclty do you mean? Check the role before every usage in the service? – Dimich Parkhomchuk Jan 11 '16 at 15:32
  • That's how I'd do it; the user invokes some function call, and the call checks to see if that user is allowed to make that call. If yes, the code executes. If not, there's an 'unauthorized access' flag thrown. – Michael McPherson Jan 11 '16 at 15:38
  • So you will check is user allowed to make that call without custom attribute? – Dimich Parkhomchuk Jan 11 '16 at 15:52
  • Well, I don't know anything about your custom attribute, so I posited a way it might work and left it at that. You'd know better than me how to properly apply the attribute you created. – Michael McPherson Jan 11 '16 at 18:22