單點登錄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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章