在我的服务层中传递 http servlet 响应是一个不好的做法吗?
在我的authenticationService 的登录方法中,我需要创建一个cookie 并在cookie 中设置会话ID。
将请求对象传递到控制器操作内的服务层是一种不好的做法吗?
public void login(String email, String password) {
User user = someService.validate(email, password);
if(user != null) {
// create session
// set cookie ????
}
}
我的控制器操作将调用上面的登录方法,但我很困惑应该在哪里为 cookie 创建和设置会话 ID。
对我来说,将其放在服务层中是有意义的,但随后我的登录方法将紧密绑定到 Web 应用程序。
我这样做对吗?
In my login method of my authenticationService, I need to create a cookie and set the session ID in the cookie.
Is it bad practise to pass the request object to my service layer inside of a controllers action?
public void login(String email, String password) {
User user = someService.validate(email, password);
if(user != null) {
// create session
// set cookie ????
}
}
My controller action will call the login method above, confused where I should be creating and setting the session id for my cookie.
It makes sense to me to have this in the service layer, but then my login method is then tightly bound to a web application.
Am I doing this right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是(“不好的做法”),否(“正确做这件事”)。
服务层应该与任何与网络有关的东西完全解耦。 Web 层应该单独负责管理 Web 层工件,包括 cookie。
这样,即使 cookie 不存在(例如桌面或 CLI 应用程序),也可以使用该服务。它还允许在完全不考虑 Web 层的情况下测试服务,这是有道理的——服务不关心身份验证如何发生,或者之后发生什么——只关心使用用户名和密码作品。
Yes (to "bad practice"), no (to "doing this right").
The service layer should be completely decoupled from anything having to do with the web. The web layer alone should be responsible for managing web-layer artifacts, including cookies.
This way the service can be used even when cookies don't exist, like a desktop or CLI app. It also allows testing the service without considering the web-layer at all, which makes sense--the service doesn't care how authentication happens, or what happens after--only that using a username and password works.
是的。尝试尽快将网络消息转换为域对象,并且在确定整个消息格式正确且经过授权之前不要采取任何操作。
如果您可以将处理混乱的不受信任输入的代码与实现业务规则并根据域对象执行更改的代码与格式化对外界的响应的代码隔离开来,您的代码将更加可维护和安全。
如果您可以将服务分为:
那么您可以集中精力对 2 进行单元测试,无需担心创建和填充存根请求和响应对象。
Yes. Try to turn network messages into domain objects as soon as possible, and don't take any actions until you've decided that the whole message is well-formed and authorized.
Your code will be more maintainable and secure if you can isolate the code that deals with messy untrusted inputs from the code that implements business rules, and enacts changes based on domain objects, from the code that formats a response to the outside world.
If you can separate your service into:
then you can focus unit-testing on 2 without worrying about creating and populating stub request and response objects.