Search code examples
c#asp.net-mvcentity-frameworkunit-of-workn-tier-architecture

Passing User identity through n-tier application


I have an MVC.Net application that is separated out into tiers containing Repositories, Business logic and front end services for AngularJS and MVC Controllers.

The repositories are currently stand alone and not wrapped in a unit of work pattern. This refactoring is going to take place.

I wanted to query with people what in their experience is the most efficient way to carry the current logged in user through the various tiers to enable security at the repository level.

At the moment I have a UserLogic class that maintains a reference to the current logged in user's Entity. This UserLogic class is then injected into controllers/business logic etc... But I suspect that's a fairly convoluted mechanism to use!


Solution

  • One approach could be to have any given repository require a user context upon instantiation. Something like this:

    public class WidgetRepository
    {
        private UserContext User { get; set; }
    
        public WidgetRepository(UserContext user)
        {
            if (user == null)
                throw new ArgumentNullException("user");
            // maybe also confirm that it's a *valid* user in some way?
            User = user;
        }
    
        // repository operations
    }
    

    You can employ as much "defensive programming" in that constructor as you like, I suppose. Then in the repository operations you can filter queries based on that user. Something like:

    public IEnumerable<Widget> Widgets
    {
        get
        {
            return dbContext.Widgets.Where(w => w.Owner.Id == User.Id);
        }
    }
    

    This would filter all widgets by the user who owns them transparently to the application.

    Keep in mind that there are trade-offs with this sort of thing. Doing this could work really well in some scenarios, not so well in others. If the DAL is transparently filtering data based on user context, then it could become quite difficult to perform system (non-user) operations or administrative (super-user) operations with the same DAL. It's impossible to say if that's going to be a problem with my current knowledge of your system, this is just a heads-up on issues I've seen come up in the past.