cas4.2.7新增驗(yàn)證碼校驗(yàn)

新增類

驗(yàn)證碼controller,用于返回圖片

package org.jasig.cas;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by wangwei on 2017/7/18.
 */
public class CaptchaImageCreateController implements Controller,InitializingBean {

    @Override
    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
        ValidatorCodeUtil.ValidatorCode codeUtil = ValidatorCodeUtil.getCode();

        request.getSession().setAttribute( "code", codeUtil.getCode());
        // 禁止圖像緩存。
        response.setHeader( "Pragma", "no-cache" );
        response.setHeader( "Cache-Control", "no-cache" );
        response.setDateHeader( "Expires", 0);
        response.setContentType( "image/jpeg");

        ServletOutputStream sos = null;
        try {
            // 將圖像輸出到 Servlet輸出流中。
            /*System.out.println("=========***********=============");*/
            sos = response.getOutputStream();
/*            System.out.println(codeUtil.getImage().toString());
            System.out.println("==============================");*/
            ImageIO.write(codeUtil.getImage(),"JPEG",sos);
           /* JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos) ;
            encoder.encode();*/
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != sos) {
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null ;

    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

}

驗(yàn)證碼圖片util

package org.jasig.cas;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ValidatorCodeUtil {

    public static ValidatorCode getCode() {
        // 驗(yàn)證碼圖片的寬度。
        int width = 120;
        // 驗(yàn)證碼圖片的高度。
        int height = 40;
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB );
        Graphics2D g = buffImg.createGraphics();

        // 創(chuàng)建一個隨機(jī)數(shù)生成器類。
        Random random = new Random();

        // 設(shè)定圖像背景色(因?yàn)槭亲霰尘埃云?
        g.setColor(Color. WHITE);
        g.fillRect(0, 0, width, height);
        // 創(chuàng)建字體,字體的大小應(yīng)該根據(jù)圖片的高度來定。
        Font font = new Font("", Font.HANGING_BASELINE, 28);
        // 設(shè)置字體。
        g.setFont(font);

        // 畫邊框。
        g.setColor(Color. BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        // 隨機(jī)產(chǎn)生155條干擾線,使圖象中的認(rèn)證碼不易被其它程序探測到。
        // g.setColor(Color.GRAY);
        // g.setColor(getRandColor(160, 200));
        // for (int i = 0; i < 155; i++) {
        // int x = random.nextInt(width);
        // int y = random.nextInt(height);
        // int xl = random.nextInt(12);
        // int yl = random.nextInt(12);
        // g.drawLine(x, y, x + xl, y + yl);
        // }

        // randomCode用于保存隨機(jī)產(chǎn)生的驗(yàn)證碼,以便用戶登錄后進(jìn)行驗(yàn)證。
        StringBuffer randomCode = new StringBuffer();

        // 設(shè)置默認(rèn)生成4個驗(yàn)證碼
        int length = 4;
        // 設(shè)置備選驗(yàn)證碼:包括"a-z"和數(shù)字"0-9"
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ;

        int size = base.length();

        // 隨機(jī)產(chǎn)生4位數(shù)字的驗(yàn)證碼。
        for (int i = 0; i < length; i++) {
            // 得到隨機(jī)產(chǎn)生的驗(yàn)證碼數(shù)字。
            int start = random.nextInt(size);
            String strRand = base.substring(start, start + 1);

            // 用隨機(jī)產(chǎn)生的顏色將驗(yàn)證碼繪制到圖像中。
            // 生成隨機(jī)顏色(因?yàn)槭亲銮熬埃云?
            // g.setColor(getRandColor(1, 100));

            // 調(diào)用函數(shù)出來的顏色相同,可能是因?yàn)榉N子太接近,所以只能直接生成
            g.setColor( new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(strRand, 15 * i + 6, 24);

            // 將產(chǎn)生的四個隨機(jī)數(shù)組合在一起。
            randomCode.append(strRand);
        }

        // 圖象生效
        g.dispose();
        ValidatorCode code = new ValidatorCode();
        code.image = buffImg;
        code.code = randomCode.toString();
        return code;
    }

    public static ValidatorCode getCodeNew() {
        int width = 200;
        int height = 60;
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB); // 創(chuàng)建BufferedImage類的對象
        Graphics g = image.getGraphics(); // 創(chuàng)建Graphics類的對象
        Graphics2D g2d = (Graphics2D) g; // 通過Graphics類的對象創(chuàng)建一個Graphics2D類的對象
        Random random = new Random(); // 實(shí)例化一個Random對象
        Font mFont = new Font("華文宋體", Font.BOLD, 30); // 通過Font構(gòu)造字體
        g.setColor(getRandColor(200, 250)); // 改變圖形的當(dāng)前顏色為隨機(jī)生成的顏色
        g.fillRect(0, 0, width, height); // 繪制一個填色矩形

        // 畫一條折線
        BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL); // 創(chuàng)建一個供畫筆選擇線條粗細(xì)的對象
        g2d.setStroke(bs); // 改變線條的粗細(xì)
        g.setColor(Color.DARK_GRAY); // 設(shè)置當(dāng)前顏色為預(yù)定義顏色中的深灰色
        int[] xPoints = new int[3];
        int[] yPoints = new int[3];
        for (int j = 0; j < 3; j++) {
            xPoints[j] = random.nextInt(width - 1);
            yPoints[j] = random.nextInt(height - 1);
        }
        g.drawPolyline(xPoints, yPoints, 3);
        // 生成并輸出隨機(jī)的驗(yàn)證文字
        g.setFont(mFont);
        String sRand = "";
        int itmp = 0;
        for (int i = 0; i < 4; i++) {
            if (random.nextInt(2) == 1) {
                itmp = random.nextInt(26) + 65; // 生成A~Z的字母
            } else {
                itmp = random.nextInt(10) + 48; // 生成0~9的數(shù)字
            }
            char ctmp = (char) itmp;
            sRand += String.valueOf(ctmp);
            Color color = new Color(20 + random.nextInt(110),
                    20 + random.nextInt(110), 20 + random.nextInt(110));
            g.setColor(color);
            /**** 隨機(jī)縮放文字并將文字旋轉(zhuǎn)指定角度 **/
            // 將文字旋轉(zhuǎn)指定角度
            Graphics2D g2d_word = (Graphics2D) g;
            AffineTransform trans = new AffineTransform();
            trans.rotate(random.nextInt(45) * 3.14 / 180, 15 * i + 10, 7);
            // 縮放文字
            float scaleSize = random.nextFloat() + 0.8f;
            if (scaleSize > 1.1f)
                scaleSize = 1f;
            trans.scale(scaleSize, scaleSize);
            g2d_word.setTransform(trans);
            /************************/
            g.drawString(String.valueOf(ctmp), 30 * i + 40, 16);

        }
        g.dispose();
        ValidatorCode code = new ValidatorCode();
        code.image = image;
        code.code = sRand.toString();
        return code;
    }

    // 給定范圍獲得隨機(jī)顏色
    static Color getRandColor( int fc, int bc) {
        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    /**
     *
     * <p class="detail">
     * 驗(yàn)證碼圖片封裝
     * </p>
     *
     *
     */
    public static class ValidatorCode {
        private BufferedImage image ;
        private String code ;

        /**
         * <p class="detail">
         * 圖片流
         * </p>
         *
         * @return
         */
        public BufferedImage getImage() {
            return image ;
        }

        /**
         * <p class="detail">
         * 驗(yàn)證碼
         * </p>
         *
         * @return
         */
        public String getCode() {
            return code ;
        }
    }
}

新增UsernamePasswordCredentialWithAuthCode類,繼承UsernamePasswordCredential,添加了驗(yàn)證碼參數(shù)

package org.jasig.cas.authentication;

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

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

/**
 * Created by wangwei on 2017/7/18.
 */
public class UsernamePasswordCredentialWithAuthCode extends UsernamePasswordCredential{

    /**
     * 帶驗(yàn)證碼的登錄界面
     */
    private static final long serialVersionUID = 1L;
    /** 驗(yàn)證碼*/
    @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;
    }

    @Override
    public 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;
    }

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

新增AuthenticationViaFormActionWithAuthCode類,繼承AuthenticationViaFormAction,添加了驗(yàn)證碼校驗(yàn)

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.stereotype.Component;
import org.springframework.webflow.execution.RequestContext;

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

/**
 * Created by wangwei on 2017/7/18.
 */
@Component("authenticationViaFormActionWithAuthCode")
public class AuthenticationViaFormActionWithAuthCode extends AuthenticationViaFormAction {

    private String CODE = "code";
    /**
     * 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(CODE);
        session.removeAttribute(CODE);

        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

  • NullAuthcodeAuthenticationException
package org.jasig.cas.authentication;

/**
 * Created by wangwei on 2017/7/18.
 */
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);
    }
}
  • BadAuthcodeAuthenticationException
package org.jasig.cas.authentication;

/**
 * Created by wangwei on 2017/7/18.
 */
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);
    }
    
}

配置修改

web.xml新增圖片獲取

<servlet-mapping>
    <servlet-name>cas</servlet-name>
    <url-pattern>/captcha.jpg</url-pattern>
</servlet-mapping>

applicationContext.xml

  • 新增bean說明
<bean id="captchaImageCreateController" class="org.jasig.cas.CaptchaImageCreateController"/>
  • 在handlerMappingC中添加/captcha.jpg映射,<prop key="/captcha.jpg">captchaImageCreateController</prop>,具體內(nèi)容如下:
<bean id="handlerMappingC" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
      p:order="1000"
      p:alwaysUseFullPath="true">
    <property name="mappings">
        <util:properties>
            <prop key="/authorizationFailure.html">passThroughController</prop>
            <prop key="/statistics/ping">pingController</prop>
            <prop key="/statistics/threads">threadsController</prop>
            <prop key="/statistics/metrics">metricsController</prop>
            <prop key="/statistics/healthcheck">healthController</prop>
            <prop key="/captcha.jpg">captchaImageCreateController</prop>
        </util:properties>
    </property>
</bean>

login-webflow.xml修改

  • 修改credential屬性,修改為新增的UsernamePasswordCredentialWithAuthCode,具體如下:
<var name="credential" class="org.jasig.cas.authentication.UsernamePasswordCredentialWithAuthCode"/>
  • 在viewLoginForm的binder中新增authcode參數(shù),并新增一個transition步驟,具體如下:
<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="authenticationViaFormActionWithAuthCode.validatorCode(flowRequestContext, flowScope.credential, messageContext)" />
    <transition on="error" to="viewLoginForm" />
    <transition on="success" to="realSubmit" />
</action-state>

messages_zh_CN.properties新增

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

頁面修改

  • 在casLoginView.jsp新增驗(yàn)證碼,代碼如下:
<section class="row">
        <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"
                                cssStyle="margin-left: 10px;" />
                </td>
                <td style="vertical-align: bottom;">
                    ![](captcha.jpg?)
                </td>
            </tr>
        </table>
    </section>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,983評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,216評論 4 61
  • 今年闊別已久的變形計重新登上熒屏,刮起一陣旋風(fēng)。 “社會我麗姐,人野路子多,社會我穎哥,人慫話還多”反正我是被吸引...
    yike11閱讀 414評論 0 0
  • 溪水潺潺 繞過那危聳的山峰 流過那茂密的叢林 來到你的身旁 問一句 你最近過得好嗎? 微風(fēng)習(xí)習(xí) 越過那蜿蜒的道路 ...
    心誠兒閱讀 182評論 0 2

友情鏈接更多精彩內(nèi)容