【发布时间】:2014-08-24 21:55:56
【问题描述】:
我有 index.jsp 发布到 `j_spring_security_check.我正在尝试将文本框值设置为 Session 变量。
下面是我的 index.jsp
<form id="loginForm" name="loginForm" method="post" action="j_spring_security_check" autocomplete="off">
<label>email address</label>
<input type="text" name="j_username" id="username" autocorrect="off" autocapitalize="off" autocomplete="off" placeholder="email address" title="email address" />
<label>password</label>
<input type="password" name="j_password" id="password" autocorrect="off" autocapitalize="off" autocomplete="off" placeholder="password" title="password" />
<button type="submit" onclick="this.disabled=true; this.form.submit.click();"><spring:message code="v2.login.button" /></button>
</form>
我试图在 Session 中设置用户名值,但表单发布到 j_spring_security_check,我真的不知道 Spring Security 是如何工作的,所以我不确定在哪里添加逻辑以将用户名值放入会话中。我想知道如果可以的话我在哪里添加逻辑是否可行?
解决方案:当一个登录表单发布到 /j_spring_security_check UsernamePasswordAuthenticationFilter 被调用来验证用户。以下是将用户名放入会话的更改 在 security-applicationContext.xml 中添加了 customUsernamePasswordAuthenticationFilter,如下所示
<beans:bean id="customUsernamePasswordAuthenticationFilter" class="com.datacert.core.security.filter.CustomUsernamePasswordAuthenticationFilter" >
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="authenticationFailureHandler" ref="DCAuthenticationFailureHandler" />
<beans:property name="authenticationSuccessHandler" ref="DCAuthenticationSuccessHandler" />
</beans:bean>
并创建了一个在会话中设置用户名的类
@Primary
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
public CustomUsernamePasswordAuthenticationFilter() {
super();
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
/*
* String username = super.obtainUsername(request); if (username != null && !StringUtils.isEmpty(username)) {
* HttpSession session = request.getSession(); session.setAttribute("username", username); }
*/
return super.attemptAuthentication(request, response);
}
}
【问题讨论】: