I have a Windows authenticated MVC application with a repository layer. All interaction by the controller with the database is done through the repository. Each controller has a reference to the repository:
public class PostController : Controller
{
private Repository db = new Repository();
[HttpPost]
public ActionResult DeletePost(int id)
{
// Authorize that the user is allowed to delete this post...
db.DeletePost(id);
}
}
My question is whether there is a good way to move my authorization logic into the repository layer. I'd like the Repository.DeletePost()
function to refuse to delete posts that were not created by the authenticated user. The problem is that my repository does not know who the authenticated user is. The controller knows (via Controller.User
).
Passing the Controller.User
into the Repository
constructor doesn't work, because the Controller.User
is apparently not defined at the time when the constructor is called.
How can I inform the Repository
of who the authenticated user is? Would it be best to just construct the Repository
within each action? Or is it a bad idea to handle it in the repository layer?
Or is it a bad idea to handle it in the repository layer?
I think the Controller is a better place for your authorization. Let the repository be a gateway to the data and the controller be a gatekeeper to your application. I'd expect to see authorization/authentication logic as early in the life-cycle as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With