单点登录CAS使用记(四):为登录页面加上验证码

CAS默认的登录页面样式如下,只有用户名与密码两项验证项目。

现在需要为首页登录加上验证码功能。

第一步:首页对默认登录页面的样式进行了调整,使其看上去还算美观。

在页面上加上了验证码项目。

 

第二步:导入验证码生成工具包及生成验证码配置

pom.xml中加入如下配置

<dependency>
    <groupId>com.google.code.kaptcha</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

 

web.xml中加入如下配置(只配置了宽高度等其他默认)

    <servlet>
        <servlet-name>captchacode</servlet-name>
        <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
        <init-param>
            <description>边框粗细度。必须是一个大于0的值</description>
            <param-name>kaptcha.border.thickness</param-name>
            <param-value>1</param-value>
        </init-param>
        <init-param>
            <description>图片的宽度</description>
            <param-name>kaptcha.image.width</param-name>
            <param-value>140</param-value>
        </init-param>
        <init-param>
            <description>图片的高度</description>
            <param-name>kaptcha.image.height</param-name>
            <param-value>55</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>captchacode</servlet-name>
        <url-pattern>/captchacode</url-pattern>
    </servlet-mapping>

 

登录页jsp中

<form:input cssClass="required" cssErrorClass="error" id="imgverifycode" path="imgverifycode" htmlEscape="true" autocomplete="off" placeholder="输入验证码" />
<img id="cimg" src="${base_path}/captchacode" onclick="refreshcaptchacode(this)" title="看不清?点击更换另一个。"/>

 JavaScript:

function refreshcaptchacode(obj) {
    obj.setAttribute("src", base_path+ "/captchacode?date=" + new Date());
}

 

第三步:CAS源码需要做哪些修改?

1.首先将新增项目imgverifycode绑定到表单

打开login-webflow.xml,找到这一段

    <view-state id="viewLoginForm" view="casLoginView" model="credentials">
        <binder>
            <binding property="username" />
            <binding property="password" />
        </binder>
        <on-entry>
            <set name="viewScope.commandName" value="'credentials'" />
        </on-entry>
        <transition on="submit" bind="true" validate="true" to="realSubmit">
            <evaluate expression="authenticationViaFormAction.doBind(flowRequestContext, flowScope.credentials)" />
        </transition>
    </view-state>

 

修改为(注意红色加大部分):

    <view-state id="viewLoginForm" view="casLoginView" model="credentials">
        <binder>
            <binding property="username" />
            <binding property="password" />
            <binding property="imgverifycode" />
        </binder>
        <on-entry>
            <set name="viewScope.commandName" value="'credentials'" />
        </on-entry>
        <transition on="submit" bind="true" validate="true" to="imgverifycodeValidate">
            <evaluate expression="authenticationViaFormAction.doBind(flowRequestContext, flowScope.credentials)" />
        </transition>
    </view-state>

    <!--  并增加了下面这一段代码 -->
    <action-state id="imgverifycodeValidate">
        <evaluate
            expression="authenticationViaFormAction.validatorCode(flowRequestContext, flowScope.credentials, messageContext)" />
        <transition on="error" to="generateLoginTicket" />
        <transition on="success" to="realSubmit" />
    </action-state>

 

主要是在登录的工作流中加上了 验证码提交绑定以及验证码验证处理。

其次,在UsernamePasswordCredentials.java中添加验证码字段。

    /** The imgverifycode. */
    @NotNull
    @Size(min = 1, message = "required.imgverifycode")
    private String imgverifycode;

对于的修改一下equals,hascode方法。

 View Code

 

2.添加验证逻辑

注意上一段配置加上了一个action-state:imgverifycodeValidate,执行的是AuthenticationViaFormAction.validatorCode(...)方法

打开AuthenticationViaFormAction.java(cas-server-core工程下),添加如下方法

    public final String validatorCode(final RequestContext context,
            final Credentials credentials, final MessageContext messageContext)
            throws Exception
    {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        HttpSession session = request.getSession();
        
        UsernamePasswordCredentials upc = (UsernamePasswordCredentials) credentials;
        String submitAuthcode = upc.getImgverifycode();
        
        if (!StringUtils.hasText(submitAuthcode))
        {
            populateErrorsInstance(new NullImgVerifyCodeAuthenticationException(),
                    messageContext);
            return "error";
        }
        
        if (StringUtils.equalsIgnoreCase((String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY), captchacode))
        {
            return "success";
        }
        populateErrorsInstance(new BadImgVerifyCodeAuthenticationException(),
                messageContext);
        return "error";
    }

 

其中NullImgVerifyCodeAuthenticationException,BadImgVerifyCodeAuthenticationException是仿照源码异常类新增的自定义异常类。

NullImgVerifyCodeAuthenticationException.java

 View Code

BadImgVerifyCodeAuthenticationException.java

 View Code

并且,在messages_zh_CN.properties文件中添加对应上面两个异常类的两个异常消息

required.imgverifycode=请输入验证码
error.authentication.imgverifycode.bad=验证码错误

 

 3.验证

 

OK。

————————————————————————————————————————————————————————————

单点登录CAS使用记系列:

posted @ 2018-05-09 20:28  舞羊  阅读(456)  评论(0编辑  收藏  举报