简体   繁体   中英

Web API C# - Role based access

I have a web app with three different user roles Admin, Reseller and Seller. Each seller is connected to a Reseller.

Lets say that we want to display a list of sellers, when the reseller makes a request to the API: GET: api/v1/members/sellers

The expected result would be all the sellers connected to that reseller. The controller could looks something like this:

[HttpGet]
[MemberAuthorize(AllowGroup = "Admin,Reseller")]
[Route("sellers")]
public HttpResponseMessage GetSellers()
{
    var member = _memberHelper.GetCurrentMember();
    if (member.Role == "Reseller")
        return sellersByReseller;
    if (member.Role == "Admin")
        return getAllSellers;

    ...
}

This would work but in my eyes it does not look pretty, and hard to test.

Is there another approach with the C# Web API that you could use for this? Something similar to this would be really neat:

[HttpGet]
[MemberAuthorize(AllowGroup = "Reseller")]
[Route("sellers")]
public HttpResponseMessage GetSellers()
{
    getSellersByReseller;
}

[HttpGet]
[MemberAuthorize(AllowGroup = "Admin")]
[RoutePrefix("sellers")]
public HttpResponseMessage GetSellersAsAdmin()
{
    getAllSellers;
}

I don't think you'll be able to split it up like that, mainly because role-based authentication is not mutually exclusive. Ie there should be nothing preventing a user from having both the "Admin" role and the "Reseller" role. How would the routing behave in that case? Ie which controller action should then be called?


What I would suggest anyway is for you to split it up into two separate routes pretty much like you've already suggested:

[HttpGet]
[MemberAuthorize(AllowGroup = "Reseller")]
[Route("reseller/sellers")]
public HttpResponseMessage GetSellersByReseller()
{
    return getSellersByReseller;
}

[HttpGet]
[MemberAuthorize(AllowGroup = "Admin")]
[RoutePrefix("admin/sellers")]
public HttpResponseMessage GetAllSellers()
{
    return getAllSellers;
}

Whether the naming of the routes makes sense is for you to choose. The bottom line is that I would suggest avoiding having one route return different results. Yes, they both return a list of sellers but the premise is different and not just defined by eg a search term which would be acceptable for one route. Now, the two routes clearly are meant for two different things/audiences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM