本文的是以cas-4.1.5进行的,cas源代码下载官网:https://apereo.github.io/cas/4.2.x/index.html。

1、在cas工程的web.xml增加验证码功能的支持:

 <!-- 验证码功能 --><servlet><servlet-name>Kaptcha</servlet-name><servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class><init-param><param-name>kaptcha.border</param-name><param-value>no</param-value></init-param><init-param><param-name>kaptcha.textproducer.char.space</param-name><param-value>5</param-value></init-param><init-param><param-name>kaptcha.textproducer.char.length</param-name><param-value>5</param-value></init-param></servlet><servlet-mapping><servlet-name>Kaptcha</servlet-name><url-pattern>/captcha.jpg</url-pattern></servlet-mapping>

2、新建一个类UsernamePasswordCredentialWithAuthCode,该类继承了

org.jasig.cas.authentication.UsernamePasswordCredential,添加一个验证码字段,

并且重写equals和hashCode方法,添加关于验证码比较的信息:

package org.spire.cas.core.authentication;import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.jasig.cas.authentication.UsernamePasswordCredential;public class UsernamePasswordCredentialWithAuthCode extendsUsernamePasswordCredential {/*** 带验证码的登录界面*/private static final long serialVersionUID = 1L;/** 验证码*/@NotNull@Size(min = 1, message = "required.authcode")private String authcode;/*** * @return*/public final String getAuthcode() {return authcode;}/*** * @param authcode*/public final void setAuthcode(String authcode) {this.authcode = authcode;}@Overridepublic boolean equals(final Object o) {if (this == o) {return true;}if (o == null || getClass() != o.getClass()) {return false;}final UsernamePasswordCredentialWithAuthCode that = (UsernamePasswordCredentialWithAuthCode) o;if (getPassword() != null ? !getPassword().equals(that.getPassword()): that.getPassword() != null) {return false;}if (getPassword() != null ? !getPassword().equals(that.getPassword()): that.getPassword() != null) {return false;}if (authcode != null ? !authcode.equals(that.authcode): that.authcode != null)return false;return true;}@Overridepublic int hashCode() {return new HashCodeBuilder().append(getUsername()).append(getPassword()).append(authcode).toHashCode();}}

3.新建一个类AuthenticationViaFormActionWithAuthCode,该类继承了org.jasig.cas.web.flow.AuthenticationViaFormAction类,增加一个验证码方法validatorCode:

package org.spire.cas.core.authentication;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.authentication.Credential;
import org.jasig.cas.authentication.RootCasException;
import org.jasig.cas.web.flow.AuthenticationViaFormAction;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.webflow.execution.RequestContext;/*** 验证码校验类* * @author Langyou02**/
public class AuthenticationViaFormActionWithAuthCode extendsAuthenticationViaFormAction {/*** authcode check*/public final String validatorCode(final RequestContext context,final Credential credentials, final MessageContext messageContext)throws Exception {final HttpServletRequest request = WebUtils.getHttpServletRequest(context);HttpSession session = request.getSession();String authcode = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);session.removeAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);UsernamePasswordCredentialWithAuthCode upc = (UsernamePasswordCredentialWithAuthCode) credentials;String submitAuthcode = upc.getAuthcode();if (StringUtils.isEmpty(submitAuthcode)|| StringUtils.isEmpty(authcode)) {populateErrorsInstance(new NullAuthcodeAuthenticationException(),messageContext);return "error";}if (submitAuthcode.equals(authcode)) {return "success";}populateErrorsInstance(new BadAuthcodeAuthenticationException(),messageContext);return "error";}private void populateErrorsInstance(final RootCasException e,final MessageContext messageContext) {try {messageContext.addMessage(new MessageBuilder().error().code(e.getCode()).defaultText(e.getCode()).build());} catch (final Exception fe) {logger.error(fe.getMessage(), fe);}}
}

其中NullAuthcodeAuthenticationException和BadAuthcodeAuthenticationException是自定义的异常类,用于取得异常码:

/** Licensed to Jasig under one or more contributor license* agreements. See the NOTICE file distributed with this work* for additional information regarding copyright ownership.* Jasig licenses this file to you under the Apache License,* Version 2.0 (the "License"); you may not use this file* except in compliance with the License.  You may obtain a* copy of the License at the following location:**   http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing,* software distributed under the License is distributed on an* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY* KIND, either express or implied.  See the License for the* specific language governing permissions and limitations* under the License.*/
package org.spire.cas.core.authentication;import org.jasig.cas.authentication.RootCasException;/*** The exception to throw when we know the authcode is null* * @author Scott Battaglia* @version $Revision$ $Date$* @since 3.0*/
public class NullAuthcodeAuthenticationException extends RootCasException {/** Serializable ID for unique id. */private static final long serialVersionUID = 5501212207531289993L;/** Code description. */public static final String CODE = "required.authcode";/*** Constructs a TicketCreationException with the default exception code.*/public NullAuthcodeAuthenticationException() {super(CODE);}/*** Constructs a TicketCreationException with the default exception code and* the original exception that was thrown.* * @param throwable the chained exception*/public NullAuthcodeAuthenticationException(final Throwable throwable) {super(CODE, throwable);}}/** Licensed to Jasig under one or more contributor license* agreements. See the NOTICE file distributed with this work* for additional information regarding copyright ownership.* Jasig licenses this file to you under the Apache License,* Version 2.0 (the "License"); you may not use this file* except in compliance with the License.  You may obtain a* copy of the License at the following location:**   http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing,* software distributed under the License is distributed on an* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY* KIND, either express or implied.  See the License for the* specific language governing permissions and limitations* under the License.*/
package org.spire.cas.core.authentication;import org.jasig.cas.authentication.RootCasException;/*** The exception to throw when we know the authcoe is not correct* * @author Scott Battaglia* @version $Revision$ $Date$* @since 3.0*/
public class BadAuthcodeAuthenticationException extends RootCasException {/** Serializable ID for unique id. */private static final long serialVersionUID = 5501212207531289993L;/** Code description. */public static final String CODE = "error.authentication.authcode.bad";/*** Constructs a TicketCreationException with the default exception code.*/public BadAuthcodeAuthenticationException() {super(CODE);}/*** Constructs a TicketCreationException with the default exception code and* the original exception that was thrown.* * @param throwable the chained exception*/public BadAuthcodeAuthenticationException(final Throwable throwable) {super(CODE, throwable);}}

4、在spire_cas工程的login_webflow.xml修改登录验证流程:

 <view-state id="viewLoginForm" view="casLoginView" model="credential"><binder><binding property="username" required="true"/><binding property="password" required="true"/><binding property="authcode" required="true"/><binding property="rememberMe" /></binder><on-entry><set name="viewScope.commandName" value="'credential'"/><!--<evaluate expression="samlMetadataUIParserAction" />--></on-entry><transition on="submit" bind="true" validate="true" to="authcodeValidate"></transition>  </view-state><action-state id="authcodeValidate">    <evaluate expression="authenticationViaFormAction.validatorCode(flowRequestContext, flowScope.credential, messageContext)" />    <transition on="error" to="generateLoginTicket" />    <transition on="success" to="realSubmit" />    </action-state>  

并修改cas-servlet.xmlbean id ="AuthenticationViaFormAction"的class="org.spire.cas.core.authentication.AuthenticationViaFormActionWithAuthCode";

5、增加国际化显示信息:

screen.welcome.label.authcode=\u9A8C\u8BC1\u7801:

screen.welcome.label.authcode.accesskey=a

required.authcode=\u5FC5\u987B\u5F55\u5165\u9A8C\u8BC1\u7801\u3002

error.authentication.authcode.bad=\u9A8C\u8BC1\u7801\u8F93\u5165\u6709\u8BEF\u3002

6、登录页面casLoginView.jsp添加验证码输入框:

 <section class="row fl-controls-left"><label for="authcode"><spring:message code="screen.welcome.label.authcode" /></label><spring:message code="screen.welcome.label.authcode.accesskey" var="authcodeAccessKey" /><table><tr><td><form:input cssClass="required" cssErrorClass="error" id="authcode" size="10" tabindex="2" path="authcode"  accesskey="${authcodeAccessKey}" htmlEscape="true" autocomplete="off" /></td><td style="vertical-align: bottom;"><img οnclick="this.src='captcha.jpg?'+Math.random()" width="93" height="30" src="captcha.jpg"></td></tr></table></section>

7、如果要默认中文页面显示,修改cas-servlet.xml 下的local Resolver默认值为zh_CN:

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" p:defaultLocale="zh_CN" />

8、效果图(spire_cas是另外一个web工程登录跳转到cas服务器认证):

9、参考博文:http://blog.csdn.net/zhu_tianwei/article/details/19153549

cas服务器登录页面添加验证码相关推荐

  1. 用来向登录页面输出验证码图片的一般处理程序页面

    这是自己以前做的B/S项目中的一个输出验证码图片的页面,没什么技术含量,希望高手们不要嘲笑,只是希望为需要帮助的人尽一点绵薄之力罢了! 页面简介:该页面是一个以ashx 为后缀的一般处理程序页面,用于 ...

  2. Vue登录页添加验证码

    登录页添加验证码 新建ValidCode组件 ​ 内容如下,直接copy即可: <template><divclass="ValidCode disabled-select ...

  3. element-plus+vite+guiplan注册页面添加验证码功能

    element-plus+vite+guiplan注册页面添加验证码功能 element-plus+vite+guiplan注册页面添加验证码功能 介绍 步骤 总结 element-plus+vite ...

  4. cas 4.1.5 添加验证码 亲测成功

    转自 http://blog.csdn.net/attackmind/article/details/52052502 1.在cas工程的web.xml增加验证码功能的支持: <!-- 验证码功 ...

  5. 登录页面带验证码html,使用H5+css3+js实现带验证码的登录页面

    使用H5+css3+js实现带验证码的登录页面 发布时间:2020-10-28 19:51:18 来源:亿速云 阅读:151 作者:Leah 本篇文章为大家展示了使用H5+css3+js实现带验证码的 ...

  6. 使用opencv破解滑块验证码:以今日头条PC端登录页面滑块验证码为例

    本文目标人群:python爬虫工程师 一.首先看看破解的效果图 二.滑块验证码的破解 滑块验证码的破解的难点主要有两个:计算出滑块到缺口的距离和模拟人拖动滑块的轨迹. 如何计算出滑块到缺口的距离?从网 ...

  7. 登录页面添加回车和单击登录事件 jQuery.ajax中的 beforeSend:function () 回调函数【日常记录】

    比较有意思的地方1: 实现如下功能可以两种方法 用jQuery.ajax中的 beforeSend:function () 回调函数:如下(下方有全部代码案例) beforeSend:function ...

  8. 为 Django admin 登录页添加验证码

    为什么80%的码农都做不了架构师?>>>    历史原因,使用上古版本 django 1.6.5,但新版本应该大同小异 首先添加自定义后台模块app, 如adm,并添加到 INSTA ...

  9. 登录验证---添加验证码验证,Cookie保存功能

    1,登录表单,login.jsp View Code 1 <%@ page contentType="text/html" pageEncoding="GBK&qu ...

最新文章

  1. ★核心关注点_《信息系统项目管理师考试考点分析与真题详解》
  2. P1996 约瑟夫问题
  3. 一文详解CMake编译工具与项目构建
  4. JNI的native代码中打印日志到eclipse的logcat中
  5. Dandan's lunch
  6. 在CentOS上配置Percona XtraDB集群(Percona XtraDB Cluster)
  7. 设计灵感|优秀案例教你如何像杂志一样排版?
  8. 【图像增强】基于matlab GUI暗通道图像去雾【含Matlab源码 740期】
  9. Redis开发与运维之第五章持久化
  10. Easyrecovery13 for mac 官方版下载
  11. 我的Java传承名单(不知为何以前的又没有了,幸亏有备份才可以又贴出来)
  12. CDH-TXKT-hive、impala
  13. 【java】JavaFX从零开始实现拼图小游戏
  14. linux 拍照软件有哪些,六款基于Linux的开源照片管理软件推荐
  15. 2020-11-28画图上的最大值点,和零基准线
  16. 全局变量global的用法
  17. PAT (Advanced Level) Practice 题解代码 - II (1051-1100)
  18. 渣基础:比照Hawstein学Cracking the coding interview(4)
  19. 关于C中编译后RO,RW,ZI的含义
  20. 电信笔试C语言,电信的几个网络方面面试笔试题汇总

热门文章

  1. 收藏!!「自然语言处理(NLP)」全球学术界知名学者教授信息大盘点(全)!
  2. [HDU6833]A Very Easy Math Problem
  3. 在 Flutter 中使用 webview_flutter 4.0 | 基础用法与事件处理
  4. 解决ecshop出现Warning: file_put_contents
  5. flutter A problem occurred evaluating project ‘:app‘.报错
  6. Norton Furbisher v1.02 Wave4(诺顿2009系列一键90天永久试用
  7. 发了几个算法的vb.net代码
  8. 机试算法讲解: 第11题 贪心之猫鼠大战
  9. 吴声:个性化规模时代来临 小程序是新商业操作系统
  10. 2021年度国内外10大低代码开发平台