[英]Should i do authorization on my Domain Services?
I have the following domain service: 我有以下域名服务:
pulic void DeleteCustomer(int customerId, string userIdentity, string userPassword)
{
//1º Do login operation to verify if the credentials are valid.
customerRepository.DeleteById(customerId);
}
Let's say that I am consuming this code of ASP.NET MVC or Windows Forms application that has a login window. 假设我正在使用具有登录窗口的ASP.NET MVC或Windows Forms应用程序的代码。
The login will be validated again in each operation, wasting resources. 每次操作都会再次验证登录名,从而浪费资源。
Let's say I change it to: 假设我将其更改为:
pulic void DeleteCustomer (int customerId, int requestUserId)
{
//1º Trust that requestUserId is valid.
//Do something with the requestUserId (e.g Set the UserId that deleted the customer)
customerRepository.DeleteById(customerId);
}
In this case, login operation will be made by the ASP.NET MVC OR Windows Forms Application just one time but any caller can pass any requestUserId, leaving a terrible security hole. 在这种情况下,登录操作将仅由ASP.NET MVC或Windows窗体应用程序执行一次,但是任何调用者都可以传递任何requestUserId,这将带来严重的安全漏洞。
While I totally agree with the logic of @KhanhTO, I would extend this with, as this is your service layer, other than attribute, i would rather inject in an authorization services interface that would do the checks with the logged in user, eg. 尽管我完全同意@KhanhTO的逻辑,但我会扩展它,因为这是您的服务层,而不是属性,我宁愿注入一个授权服务接口,该接口将对已登录用户进行检查。 to see if that he has correct permissions associated to his credentials to execute the given command.
查看他是否具有与其凭据关联的正确权限以执行给定命令。
It makes sense to do authorization in any methods that need authorization otherwise there will be a security problem, especially when these methods are entry points in your backend logic. 在需要授权的任何方法中进行授权都是有意义的,否则会存在安全性问题,尤其是当这些方法是后端逻辑中的入口点时。 That means if you deploy these domain services as another tier which is accessible from outside, these methods really need protection.
这意味着,如果将这些域服务部署为可从外部访问的另一层,则这些方法确实需要保护。
From defensive programming perspective, every method should be able to defend itself from invalid or fake inputs which is also applicable in this case. 从防御性编程的角度来看,每种方法都应该能够抵御无效或伪造的输入,这在这种情况下也适用。
From REST stateless perspective, every request should be isolated from each other which means each request should carry all the necessary information without relying on previous requests and there even should not be a server state . 从REST无状态的角度来看,每个请求都应该相互隔离 ,这意味着每个请求都应携带所有必要的信息,而不必依赖先前的请求, 甚至不应该处于服务器状态 。 For that reason, all requests should be authorized independently.
因此,所有请求均应独立授权。
Furthermore, authorization is a cross-cutting concern, you should consider writing your authorization code as an attribute. 此外,授权是一个贯穿各领域的问题,您应该考虑将授权代码作为属性编写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.