I am building a web s开发者_如何学JAVAite in C# using asp.NET MVC
How can I secure that no unauthorized persons can access my methods?
What I mean is that I want to make sure that only admins can create articles on my page. If I put this logic in the method actually adding this to the database, wouldn't I have business logic in my data layer?
Is it a good practise to have a seperate security layer that is always in between of the data layer and the business layer to make?
The problem is that if I protect at a higher level I will have to have checks on many places and it is more likely that I miss one place and users can bypass security.
Thanks!
Authorize filters (as pmarflee said) are sort of the canonical example of how to secure your controllers, though that doesn't always satisfy your requirements (e.g. if you're exposing your model through other means such as if you're also exposing a WCF service).
The more global and flexible means is to require a security service somewhere (your choice where, but commonly in either the controller or repository base) and then pass in a user context somehow (either through params or constructor). yes, that means you have to be sure to call that service in each action, but it's pretty hard to avoid that unless you decide to go with some sort of aspect-oriented programming container.
Have a look at this post, which explains how to use action filters to provide authorization on controller actions.
For your problem there are Policy base authorization: https://learn.microsoft.com/en-US/aspnet/core/security/authorization/policies?view=aspnetcore-6.0
精彩评论