views:

34

answers:

1

I'm trying to be a Good Developer and separate my concerns out. I've got an ASP.NET MVC project with all my web code, and a DAL project with all the model code.

Sometimes code in the DAL needs to check if the current user is authorized to perform some actions, by checking something like CurrentUser.IsAdmin.

For the web site, the current is derived from the Windows username (from HttpContext.Current.User.Identity), but this is clearly a web concern and shouldn't be coupled to the DAL.

What's the best pattern to loosely couple the authentication? Should the DAL be asking the MVC code for a username, or the MVC be telling the DAL? Are there advantages or disadvantages to one or the other?

Thank you!

+1  A: 

Typically I handle the security at the controller level, not at the data level. If you want to handle it at the data level, then I'd use injection to give your DAL either the current user or the means to access who the current user is. In this case it would mean injecting the User object from the Controller when you create the DAL instance. I sometimes do this for auditing, i.e., the current user may be a member of a role that allows access to a modify a user's data. In that case I want to insert the actual user making the change into the audit table. I would avoid using HttpContext.Current -- you should use the properties on the controller instead and inject them rather than having the DAL obtain them from a static object. That will make your DAL much easier to test.

When handling security in the controller you can use the AuthorizeAttribute or custom attributes derived from it to implement your cross-cutting security concerns.

tvanfosson