Resource based authorization in .net

后端 未结 5 640
故里飘歌
故里飘歌 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:57

    You need to externalize your authorization. You want to move your entire authorization logic to a separate layer or service.

    There are several frameworks - in different languages - that let you do that. In the .NET world, as suggested in the other answers, you have Claims-based authorization. Microsoft has a great article on that here.

    I would advocate you go for a standardized approach, namely XACML, the eXtensible Access Control Markup Language. XACML gives you 3 things:

    • a standard architecture with the notion of a policy decision point (the PDP - that's your authorization service) which can serve yes/no decisions
    • a standard language to express your authorization logic using any number of parameters / attributes including user attributes and resource information.
    • a request/response scheme to send your authorization questions over to the PDP.

    If we revisit your example, you would have something along the lines of:

    public Resource GetResource(int id)
    {
         var resource = resourceRepository.Find(id);
        if (isAuthorized(User.Identity,resource))
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
    
        return resource;
    }
    
    public bool isAuthorized(User u, Resource r){
       // Create XACML request here
       // Call out to PDP
       // return boolean decision
    }
    

    Your PDP would contain the following rules:

    • a user can do the action==view on a resource if and only if the resource.owner==user.id
    • a user with the role==administrator can do the action==view on a resource.

    The benefit of XACML is that you can grow your authorization rules / logic independently of your code. This means you don't have to touch your application code whenever the logic changes. XACML can also cater for more parameters / attributes - for instance a device id, an IP, the time of the day... Lastly, XACML isn't specific to .NET. It works for many different frameworks.

    You can read up on XACML here and on my own blog where I write about authorization. Wikipedia also has a decent page on the topic.

提交回复
热议问题