[英]Web API C# - Role based access
I have a web app with three different user roles Admin, Reseller and Seller.我有一个 web 应用程序,具有三个不同的用户角色管理员、经销商和卖方。 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假设我们要显示卖家列表,当经销商向 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:
controller 可能看起来像这样:
[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? C# Web API 是否有另一种方法可以用于此? 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?
即应该调用哪个 controller 动作?
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.
现在,这两条路线显然是针对两种不同的事物/观众的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.