Resource based authorization in .net

后端 未结 5 680
故里飘歌
故里飘歌 2020-12-29 11:20

Let\'s say that you have a .net web api with a GetResource(int resourceId) action. This action (with the specified id) should only be authorized for a user associated with t

5条回答
  •  清歌不尽
    2020-12-29 11:52

    I would look at implementing a custom System.Web.Http.AuthorizeAttribute which you could apply to actions that need this specific authorization rule. In the custom Authorization you can allow access if the user is a member of the Admins group, or if they are the author of the resource.

    EDIT:

    Based on OP's edit, allow me to expand what I was saying. If you override AuthorizeAttribute, you can add logic like:

    public class AuthorizeAdminsAndAuthors : System.Web.Http.AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            return currentUser.IsInRole("Admins") || IsCurrentUserAuthorOfPost(actionContext);
        }
    
        private bool IsCurrentUserAuthorOfPost(HttpActionContext actionContext)
        {
            // Get id for resource from actionContext
            // look up if user is author of this post
            return true;
        }
    

    This is pseudo-code, but should convey the idea. If you have a single AuthorizeAttribute that determines authorization based on your requirements: Current request is either from the author of the post or an Admin then you can apply AuthorizeAdminsAndAuthors Attribute to any resource where you require this level of authorization. So your resource would look like:

    [AuthorizeAdminsAndAuthors]
    public Resource GetResource(int id)
    {
        var resource = resourceRepository.Find(id);
        return resource;
    }
    

提交回复
热议问题