简体   繁体   English

spring security中的手动认证逻辑应该放在哪里 - 服务层或表示层?

[英]Where should the manual authentication logic in spring security go - Service layer or presentation layer?

I have this piece of code 我有这段代码

UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(email);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);

This is to manually authenticate a user in spring security. 这是在spring security中手动验证用户身份。 My question is where should I place this code? 我的问题是我应该在哪里放置此代码? Putting this in service layer forces me to bring the HttpSession object to service layer which AFAIK is bad. 把它放在服务层强制我将HttpSession对象带到AFAIK坏的服务层。 I am not sure about how good it is to place the authentication logic in presentation layer either. 我不确定将认证逻辑放在表示层中有多好。 Anyone with any insights?? 任何有见解的人?

Thanks in advance. 提前致谢。

Refer to Luke Taylor's answer to the question Best practice for getting active user's UserDetails? 请参阅Luke Taylor 对获得活跃用户的UserDetails的最佳实践问题的回答 for the design rationale for creating a custom interface to do this type of things while keeping your code decoupled from the Spring Security. 有关创建自定义界面以执行此类事物的设计原理,同时保持代码与Spring Security分离。 For example, you can write an interface called MyAuthenticator and write the implementation and inject it in your application. 例如,您可以编写一个名为MyAuthenticator的接口并编写实现并将其注入您的应用程序中。

Also if your spring security filters are standard then you don't need to access HttpSession object. 此外,如果您的spring安全过滤器是标准的,那么您不需要访问HttpSession对象。 Framework filters will take care of it. 框架过滤器将负责处理它。 You have to just write following in your implementation: 你必须在你的实现中写下以下内容:

UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(email);

Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());

SecurityContextHolder.getContext().setAuthentication(authentication);

I would not recommend using "SPRING_SECURITY_CONTEXT" ( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY ) as it may change in future versions of the framework. 我不建议使用“SPRING_SECURITY_CONTEXT”( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY ),因为它可能会在未来版本的框架中发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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