Custom WebApi Authorization Database Call

梦想与她 提交于 2019-12-22 10:46:14

问题


I'm trying to decide if the custom Authorization attribute I wrote is really a good idea.

Scenario
Say we have a collection of stores, each Store has an owner. Only the owner of the store can do CRUD operations on the store. EXCEPT for users with a Claim that basically overrides the ownership requirement and says they can do CRUD operations on ANY store.

Sidenote: I'm using Thinktecture and ADFS

So I made a StoreOwnerAuthorize attribute who's parameters ("Manage", "Stores") are used to check if the user has the appropriate claim to "override" not being an owner but still able to pass the authorization check.

I'm not sure how I feel about having a claim like "ManageStores" and making the database call inside the attribute. It makes me think I'm going down the wrong road, even though it does accomplish exactly what I need.

API Routes

api/v1/Store/{storeId:int:min(1)}/employees   
api/v1/Store/{storeId:int:min(1)}/inventory 

API Method

[StoreOwnerAuthorize("Manage", "Stores")]
[ResourceAuthorize("View", "Store")]
[Route("")]
//api/v1/Store/{storeId:int:min(1)}/employees 
public IHttpActionResult GetStoreEmployees(int storeId)
{
    return Ok(collectionOfStoreEmployees);
}

StoreOwnerAuthorizeAttribute

public class StoreOwnerAuthorizeAttribute : ResourceAuthorizeAttribute
{
    private readonly DbContext _context = new DbContext();

    public StoreOwnerAuthorizeAttribute(){  }
    public StoreOwnerAuthorizeAttribute(string action, params string[] resources)
        : base(action, resources) { }

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        //If the user has the Claim that overrides the requirement that the user 
        //is the Owner of the Store, skip checking if they are the owner
        if (base.IsAuthorized(actionContext))
            return true;

        //Get route parameter to lookup Store and determine if the user is the owner
        object storeId;
        actionContext.ControllerContext.RouteData.Values.TryGetValue("storeId", out storeId);
        var isOwner = false;
        if (storeId != null)
        {
            isOwner =
                _context.Store_Get_ByStoreID(int.Parse(storeId.ToString()))
                    .Any(x => x.OwnerId == theUser.Id());
        }
        return isOwner;
    }
}

来源:https://stackoverflow.com/questions/29172150/custom-webapi-authorization-database-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!