单点登录 - CAS服务器登录页添加验证码

本文CAS 版本基于 4.1.x,其它版本有可能不适用 ヾ(≧O≦)〃嗷~ヾ(≧O≦)〃嗷~

看下效果图

 

1、添加验证码生成库

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

 

2、在web.xml添加验证码生成的servlet

    <!-- 验证码 -->
    <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>

 

3、分别添加带验证码的凭证类、带验证码校验功能的表单响应类、一些对应的异常类

package org.jasig.cas.authentication;

import org.apache.commons.lang3.builder.HashCodeBuilder;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class UsernamePasswordAuthCodeCredential extends UsernamePasswordCredential {

    /**
     * 验证码
     */
    @NotNull
    @Size(min = 1, message = "required.authcode")
    private String authcode;

    public final String getAuthcode() {
        return authcode;
    }

    public final void setAuthcode(String authcode) {
        this.authcode = authcode;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final UsernamePasswordAuthCodeCredential that = (UsernamePasswordAuthCodeCredential) 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;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(getUsername())
                .append(getPassword()).append(authcode).toHashCode();
    }

}  

 

package org.jasig.cas.web.flow;

import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.authentication.*;
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;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 验证码校验类
 */
public class AuthenticationViaFormWithAuthCodeAction extends AuthenticationViaFormAction {

    public final String validateCode(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);

        UsernamePasswordAuthCodeCredential upc = (UsernamePasswordAuthCodeCredential) 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);
        }
    }
}  

 

package org.jasig.cas.web.flow;

import org.jasig.cas.authentication.RootCasException;

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);
    }
}

 

package org.jasig.cas.web.flow;

import org.jasig.cas.authentication.RootCasException;

public class NullAuthcodeAuthenticationException extends RootCasException {

    /** Serializable ID for unique id. */
    private static final long serialVersionUID = 5501212207531289993L;

    /** Code description. */
    public static final String CODE = "required.vcode";

    /**
     * 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);
    }
}

 

4、注册authenticationViaFormAction

需要把原有的authenticationViaFormAction注释

  <!--修改表单响应类-->
  <bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormWithAuthCodeAction"
        p:centralAuthenticationService-ref="centralAuthenticationService"
        p:warnCookieGenerator-ref="warnCookieGenerator"/>
<!--
  <bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"
        p:centralAuthenticationService-ref="centralAuthenticationService"
        p:warnCookieGenerator-ref="warnCookieGenerator"/>
-->

 

5、修改登录流程

cas使用spring web flow定义登录流程,加入验证码后,需要在提交表单后,在后端先验证验证码,再继续原有的流程。修改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"/>
        </binder>
        <on-entry>
            <set name="viewScope.commandName" value="'credential'"/>

            <!--
            <evaluate expression="samlMetadataUIParserAction" />
            -->
        </on-entry>

        <!--<transition on="submit" bind="true" validate="true" to="realSubmit"/>-->

        <!--添加验证码流程-->
        <transition on="submit" bind="true" validate="true" to="authcodeValidate"/>
    </view-state>

    <!--添加验证码流程-->
    <action-state id="authcodeValidate">
        <evaluate
                expression="authenticationViaFormAction.validateCode(flowRequestContext, flowScope.credential, messageContext)" />
        <transition on="error" to="generateLoginTicket" />
        <transition on="success" to="realSubmit" />
    </action-state>

除此之外,登录流程中的凭证需要换成之前定义的凭证类,需要修改login-webflow.xml

    <var name="credential" class="org.jasig.cas.authentication.UsernamePasswordAuthCodeCredential"/>
<!--
    <var name="credential" class="org.jasig.cas.authentication.UsernamePasswordCredential"/>
-->

 

6、国际化文件 messages_zh_CN.properties 添加消息

screen.welcome.label.authcode=验证码:
screen.welcome.label.authcode.accesskey=a
required.authcode=必须录入验证码。
error.authentication.authcode.bad=验证码输入有误。

其它英文的国际化文件请自行添加

 

7、修改登录页面,添加验证码的div

        <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 onclick="this.src='captcha.jpg?'+Math.random()" width="93" height="30" src="captcha.jpg">
                    </td>
                </tr>
            </table>
        </section>

 

完成上面几步后,就一切OK了

 

转载于:https://my.oschina.net/thinwonton/blog/1422880

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值