spring security中的手动认证逻辑应该放在哪里 - 服务层或表示层? [英] Where should the manual authentication logic in spring security go - Service layer or presentation layer?

查看:113
本文介绍了spring security中的手动认证逻辑应该放在哪里 - 服务层或表示层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码

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对象带到AFAIK坏的服务层。
我不确定将认证逻辑放在表示层中有多好。任何有见解的人?

This is to manually authenticate a user in 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. I am not sure about how good it is to place the authentication logic in presentation layer either. Anyone with any insights??

提前致谢。

推荐答案

请参阅Luke Taylor对问题的回答获取活动用户的UserDetails的最佳做法?用于创建自定义接口以执行此类事物的设计原理,同时保持代码与Spring Security分离。例如,您可以编写一个名为 MyAuthenticator 的接口,并编写实现并将其注入您的应用程序。

Refer to Luke Taylor's answer to the question Best practice for getting active user's 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. For example, you can write an interface called MyAuthenticator and write the implementation and inject it in your application.

如果您的spring安全过滤器是标准的,那么您不需要访问HttpSession对象。框架过滤器将负责处理它。你必须在你的实现中写下以下内容:

Also if your spring security filters are standard then you don't need to access HttpSession object. 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);

我不建议使用SPRING_SECURITY_CONTEXT( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY )因为它可能会在未来版本的框架中发生变化。

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中的手动认证逻辑应该放在哪里 - 服务层或表示层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆