http://www.itdadao.com/articles/c15a754492p0.html 基于xml 配置方式,讲的比较散。
我就再汇总一次吧!都写的散,简单,我写个特别简单的。算是给福利,如果可以,别忘了点赞。
springsecurity至少现在是不支持验证码功能,以后支持不支持,不知道。以后要是支持,省去了一部分苦逼的活。
实现方法 大都这么说,有三种方法。
可以有三种方法可以实现验证码的功能
第一种
自定义一个filter,放在SpringSecurity过滤器之前,在用户登录的时候会先经过这个filter,然后在这个filter中实现对验证码进行验证的功能,这种方法不推荐,因为它已经脱离了SpringSecurity
第二种
自定义一个filter让它继承自UsernamePasswordAuthenticationFilter,然后重写attemptAuthentication方法在这个方法中实现验证码的功能,如果验证码错误就抛出一个继承自AuthenticationException的验证吗错误的异常比如(CaptchaException),然后这个异常就会被SpringSecurity捕获到并将异常信息返回到前台,这种实现起来比较简单。
重写attemptAuthentication方法的重点部分代码
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
String requestCaptcha = request.getParameter(this.getCaptchaFieldName());
String genCaptcha = (String)request.getSession().getAttribute("code");
logger.info("开始校验验证码,生成的验证码为:"+genCaptcha+" ,输入的验证码为:"+requestCaptcha);
if( !genCaptcha.equals(requestCaptcha)){
throw new CaptchaException(
this.messageSource.getMessage("AbstractUserDetailsAuthenticationProvider.badCaptcha",null,"Default",null));
}
return super.attemptAuthentication(request, response);
}
接着在配置文件中配置:
<bean id="loginFilter" class="com.zrhis.system.security.DefaultUsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"></property>
<property name="authenticationSuccessHandler">
<bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/index.jsp"></property>
</bean>
</property>
<property name="authenticationFailureHandler">
<bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login.jsp"></property>
</bean>
</property>
</bean>
<!--http中加入custom-filter配置,将这个filter放在SpringSecurity的FORM_LOGIN_FILTER之前.-->
<custom-filter ref="loginFilter" before="FORM_LOGIN_FILTER"/>
第三种
直接替换掉SpringSecurity的UsernamePasswordAuthenticationFilter,这种比较复杂,但是更为合理,也是我现在正在用的。