我正在尝试从Spring安全性登录页面将数据库名称设置为请求输入参数。目前,我只获得使用spring security检索到的用户名SecurityContextHolder.getContext().getAuthentication()。
SecurityContextHolder.getContext().getAuthentication()
如何访问在登录页面上设置的其他字段?
详细阐述@Vacuum的评论
这是一种简单的方法(未经测试,但我相信这会起作用)
1)创建一个新类ExUsernamePasswordAuthenticationFilter,它将扩展默认过滤器并获取其他参数并将其存储在会话中。它看起来像这样:
ExUsernamePasswordAuthenticationFilter
public class ExUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { final String dbValue = request.getParameter("dbParam"); request.getSession().setAttribute("dbValue", dbValue); return super.attemptAuthentication(request, response); } }
2)在你的UserDetailsService实现中,修改你的实现:
UserDetailsService
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException;
获取第1)步中的过滤器提供的会话变量。
3)在你的<http />安全设置中,使用你的自定义过滤器覆盖默认过滤器
<http />
<custom-filter ref="beanForYourCustomFilterFromStep1" position="FORM_LOGIN_FILTER"/>
有很多方法可以做到这一点,但是正式的方法是使用custom 和,分别将Spring 和AuthenticationDetails和AuthenticationDetailsSource子类化。将多余的字段添加到自定义中,并让自定义从请求中获取数据以填充该字段。WebAuthenticationDetailsWebAuthenticationDetailsSourceWebAuthenticationDetailsWebAuthenticationDetailsSource
AuthenticationDetails
AuthenticationDetailsSource
WebAuthenticationDetailsWebAuthenticationDetailsSourceWebAuthenticationDetailsWebAuthenticationDetailsSource
在Spring Security 3.1中,使用元素的authentication-details-source-ref属性很容易配置<form-login>。
authentication-details-source-ref
<form-login>
在3.0中,你必须使用BeanPostProcessor。
BeanPostProcessor