扩展acegi以支持验证码

主要是通用改写扩展 AuthenticationProcessingFilter 类加入验证码的校验来实现,当然还有开源框架 JCaptcha 来生成验证码,验证码的生成过程可以去查阅相关的资料,这里只展示后端在验证时的扩展点,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class AuthenticationProcessingFilter implements Filter, InitializingBean, ApplicationEventPublisherAware {

// 省略非关键点代码

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
// ...
if (requiresAuthentication(httpRequest, httpResponse)) {
Authentication authResult;
try {
//加入验证码
if(!onPreAuthentication(httpRequest, httpResponse)){
httpRequest.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY,
username);
throw new AuthenticationCodeException("请输入正确的验证码!");
}
// 省略非关键代码
}

filterChain.doFilter(request, response);
}

//加入验证码
protected boolean onPreAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException {
String randNum=request.getParameter("randNum");
String rand=(String)request.getSession().getAttribute("rand");
if(rand.equals(randNum)){
return true;
}
return false;
}
// 省略非关键代码
}