I read a dozen questions regarding custom authorization filters in ASP.NET MVC, but none of them deal with what I mean.
Here is the setup:
- ASP.NET MVC 4 Project
- UserProfiles are stored in DB (EF5) and are associated with SimpleMembershipProvider with WebSecurity.InitializeDatabaseConnection. Therefore, I can always get UserProfile based on User.Identity.Name
- Each custom object has a BlogPost collection in a one-to-many relationship.
- Each BlogPost "knows" the user who owns it through the UserProfile property (thanks EF!).
Imagine that John is trying to access http://mysite.com/BlogPosts/Edit/5 and that BlogPost number 5 is Mary's blog post. John is allowed because he is logged in and he passes the built-in authorization scheme, but he does not have the right to edit Mary blos's message. Hope you get the picture.
I know about authorization in ASP.NET MVC, and I know that I can create my own custom IAuthorizationFilter. However, my authorization filter must have access to the database (DbContext in my case) to check if the object is being deleted or deleted, i.e. BlogPost number 5 belongs to the registered user. In other words, the current registered user can edit and delete his "material". Each “material” knows the user to whom it belongs.
Something like this in the alias code:
var currentlyLoggedUser = this.dbContext.UserProfiles.Single(user => user.Username == this.User.Identity.Name); if (blogPost.UserProfile != currentlyLoggedUser) {
So, my two simple questions: 1. What is the “best practice” way to access the database from a custom IAuthorizationFilter ? Should I somehow insert my IRepository (the interface serving my DbContext) into the authorization filter attribute? Should I try to find my IRepository from the controller from the OnAuthorization method of my filter? Is it possible to access the database from inside the filter in the first place? 2. If using IAuthorizationFilter for this task is not a “best practice” method, then what is it?
So, we summarize:
How can I make sure that the current registered user can edit / delete only his “things” if each “material” knows the user who owns it?
source share