我有这段代码
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);
这是在 Spring Security 中手动对用户进行身份验证。
我的问题是我应该把这段代码放在哪里?
把它放在服务层迫使我将 HttpSession 对象带到服务层,据我所知这是不好的。
我也不确定将身份验证逻辑放在表示层中有多好。有谁有见解吗??
提前致谢。
参考卢克·泰勒对问题的回答获取活跃用户的用户详细信息的最佳实践?了解创建自定义接口来执行此类操作的设计原理,同时保持代码与 Spring Security 解耦。例如,您可以编写一个名为MyAuthenticator
编写实现并将其注入您的应用程序中。
另外,如果您的 Spring 安全过滤器是标准的,那么您不需要访问 HttpSession 对象。框架过滤器会处理它。您只需在实现中编写以下内容:
UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(email);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
我不建议使用“SPRING_SECURITY_CONTEXT”(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY
),因为它可能在框架的未来版本中发生变化。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)