开发者

.NET custom authorize attribute (mvc)

开发者 https://www.devze.com 2023-01-31 06:40 出处:网络
In certain Controller I have CRUD methods. In order to access these methods user needs to be logged in. This is why I used [Authorize] attribute for this controller. Now I need additional attribute wh

In certain Controller I have CRUD methods. In order to access these methods user needs to be logged in. This is why I used [Authorize] attribute for this controller. Now I need additional attribute which would check if item that user wants to view/delete/update belongs to him.

Is it possible and recommended to do this with attribute or you would suggest using c开发者_开发知识库heck methods inside each method? If you suggest using attribute, could you please provide me some links/instructions?

EDIT:

Ofcourse, if attribute returns false than I don't want to redirect user to login page but show him an error message...


It can be done with a custom Authorize attribute, but it's much cleaner to put the logic inside your controller methods.


The attribute is related to the action being called (the controller class method). On that basis any attribute relating to the user's ownership of the object being manipulated (from your Model) should really be on the entity/class that the user is attempting to manipulate. You'll probably find it easier to validate the user within the Model method rather than using an attribute to achieve this.


In my opinion it is possible, just google for 'Custom Authorize Attribute'.

But maybe it is better to query your database with something like this:

ContextOrSession.Query<Something>.Where(Something.Groups.Intersect(User.Groups).Count>0)
0

精彩评论

暂无评论...
验证码 换一张
取 消