spring security 2安全功能,添加用户验证码的实现,方案有3个:
方案1、由于AuthenticationProcessingFilter过滤器是拦截/j_spring_security_check地址,他的实现类里只读取的j_username和j_password,
没有读取其他的用户登陆信息,所以我就把验证码(code)在login.jsp页面和j_username拼装在一起,在UserDetailServiceImpl类UserDetails loadUserByUsername(String userName)
方法里对传进的userName进行拆分,分解出用户名和验证码,剩下的工作不用我详细说了。
方案2、继承AuthenticationProcessingFilter重写一下AuthenticationProcessingFilter类的实现类,该方案的缺点是对现有的spring security 2配置改动较大;
方案3(我推荐的),优点自己体会。
步骤1写过滤器,代码如下:
package com.ss3ex.core.security.service;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CodeFilter extends HttpServlet implements Filter {
/**
* 判断用户输入的验证码是否正确
*/
private static final long serialVersionUID = -5838154525730151323L;
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String code = request.getParameter("j_code");
Cookie[] cookie = request.getCookies();
String codes = "";
for (int i = 0; cookie != null && i < cookie.length; i++) {
if ("codes".equals(cookie[i].getName())) {
codes = cookie[i].getValue();
}
}
if (!"".equals(codes) && codes != null) {
if (code.equalsIgnoreCase(codes)) {
filterChain.doFilter(request, response);
} else {
response.sendRedirect("/login.jsp?error=5");
}
} else {
response.sendRedirect("/login.jsp?error=5");
}
}
}
步骤2添加web.xml中的配置,代码如下:
<filter>
<filter-name>CodeFilter</filter-name>
<filter-class>com.ss3ex.core.security.service.CodeFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CodeFilter</filter-name>
<url-pattern>/j_spring_security_check</url-pattern>
</filter-mapping>
注意:放在<filter-name>springSecurityFilterChain</filter-name>的前面就可以了。