很多网站的用户登录,从安全上考虑.不仅需要输入用户名和密码,而且也需要输入"验证码",何为验证码这里不着解释,网上也有很多说明.下面给出在Acegi框架下的实现验证码功能的主要代码.
一.新建AuthenticationProcessingFilter 类
java 代码
- import net.sf.acegisecurity.Authentication;
- import net.sf.acegisecurity.AuthenticationException;
- import net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter;
- import javax.servlet.http.HttpServletRequest;
- import ... ...
- public class ValidationCodeFilter extends AuthenticationProcessingFilter {
- public Authentication attemptAuthentication(HttpServletRequest httpServletRequest) throws AuthenticationException{
- String inputValidationCode = httpServletRequest.getParameter( "j_validation_code" );
- //从Session中取出验证码
- String ssnValidationCode = (String)httpServletRequest.getSession().getAttribute( VALIDATION_CODE );
- if( ssnValidationCode != null && !ssnValidationCode.equals( inputValidationCode ) ){
- //用户输入的值与看到的不一致,抛出异常
- throw new ValidationCodeException( "验证码输入错误!");
- }
- return super.attemptAuthentication( httpServletRequest ) ;
- }
- }
二.新建异常类ValidationCodeException
java 代码
- import net.sf.acegisecurity.AuthenticationException;
- /**
- * 验证码异常
- */
- public class ValidationCodeException extends AuthenticationException {
- public ValidationCodeException(String s) {
- super(s);
- }
- }
三.修改Acegi配置文件
- <bean id="authenticationProcessingFilter" class="xxx.xxx.ValidationCodeFilter">
- <property name="authenticationManager"><ref local="authenticationManager"/>property>
- <property name="authenticationFailureUrl"><value>/loginFailure.htmlvalue>property>
- <property name="defaultTargetUrl"><value>/welcome.htmlvalue>property>
- <property name="filterProcessesUrl"><value>/j_security_checkvalue>property>
- bean>