CAS增加登录验证码
本来集成CAS的时候没想增加验证码的问题,这几天发部测试版本的时候,需求人员跑过来说要加个图片验证码的,当时心里确实没底,但是没说不行,然后就开始搜资料,搜了一会也没搜出什么相关的东西,加上google老报错,没办法! 还是得把源码拿出来看了,还好之前集成CAS的时候对它的目录结构和配置相关的东西了解一点,然后花了点时间看了一下login-webflow.xml的配置,大概知道怎么回事了..........
CAS版本:cas-server-3.4.11,cas-client-3.2.1
1、当然是在登录页面(casLoginView.jsp)增加验证码的输入框(这里我命名为:vcode)。
2、增加vcode输入框后,那相应的,在接收表单的java bean里面也要加上vcode属性,CAS接收和验证登录表单的java bean是UsernamePasswordCredentials,这里我是增加了一个自己的UsernamePasswordVCodeCredentials的类,当然这里要继承UsernamePasswordCredentials类;
public class UsernamePasswordVCodeCredentials extends UsernamePasswordCredentials {private static final long serialVersionUID = 1L;@NotNull @Size(min=1,message = "required.vcode")/*这里需要到相应的属性文件里面增加描述*/private String vcode;public String getVcode() {return vcode;}public void setVcode(String vcode) {this.vcode = vcode;} }
<var name="credentials" />>
<var name="credentials" />
public class MyAuthenticationViaFormAction extends AuthenticationViaFormAction {private final String ERROR="error";private final String SUCCESS="success"; public final String validatorCode(final RequestContext context, final Credentials credentials, final MessageContext messageContext) throws Exception { String vcode=(String)WebUtils.getHttpServletRequest(context).getSession().getAttribute("vcode"); UsernamePasswordVCodeCredentials upv=(UsernamePasswordVCodeCredentials)credentials; if(StringUtils.isBlank(upv.getVcode()) || StringUtils.isBlank(vcode)) return ERROR; if(upv.getVcode().equals(vcode)){ return SUCCESS; } MessageBuilder msgBuilder=new MessageBuilder(); msgBuilder.defaultText("验证码有误!"); messageContext.addMessage(msgBuilder.error().build()); return ERROR; }}
<bean id="authenticationViaFormAction" name="code"><bean id="authenticationViaFormAction" />
<view-state id="viewLoginForm" view="casLoginView" model="credentials"> <binder> <binding property="username" /> <binding property="password" /> <binding property="vcode" /> </binder> <on-entry> <set name="viewScope.commandName" value="'credentials'" /> </on-entry><transition on="submit" bind="true" validate="true" to="validatorCode"> <evaluate expression="authenticationViaFormAction.doBind(flowRequestContext, flowScope.credentials)" /> </transition></view-state><action-state id="validatorCode"><evaluate expression="authenticationViaFormAction.validatorCode(flowRequestContext, flowScope.credentials, messageContext)" /><transition on="error" to="generateLoginTicket" /><transition on="success" to="realSubmit" /></action-state> ...........