cas4.2.7新增驗證碼校驗

新增類

驗證碼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 {

    }

}

驗證碼圖片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() {
        // 驗證碼圖片的寬度疲吸。
        int width = 120;
        // 驗證碼圖片的高度。
        int height = 40;
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB );
        Graphics2D g = buffImg.createGraphics();

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

        // 設(shè)定圖像背景色(因為是做背景高诺,所以偏淡)
        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);
        // 隨機產(chǎn)生155條干擾線,使圖象中的認證碼不易被其它程序探測到牡拇。
        // 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用于保存隨機產(chǎn)生的驗證碼魁瞪,以便用戶登錄后進行驗證。
        StringBuffer randomCode = new StringBuffer();

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

        int size = base.length();

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

            // 用隨機產(chǎn)生的顏色將驗證碼繪制到圖像中。
            // 生成隨機顏色(因為是做前景剔蹋,所以偏深)
            // g.setColor(getRandColor(1, 100));

            // 調(diào)用函數(shù)出來的顏色相同旅薄,可能是因為種子太接近,所以只能直接生成
            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)生的四個隨機數(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(); // 實例化一個Random對象
        Font mFont = new Font("華文宋體", Font.BOLD, 30); // 通過Font構(gòu)造字體
        g.setColor(getRandColor(200, 250)); // 改變圖形的當前顏色為隨機生成的顏色
        g.fillRect(0, 0, width, height); // 繪制一個填色矩形

        // 畫一條折線
        BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL); // 創(chuàng)建一個供畫筆選擇線條粗細的對象
        g2d.setStroke(bs); // 改變線條的粗細
        g.setColor(Color.DARK_GRAY); // 設(shè)置當前顏色為預(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);
        // 生成并輸出隨機的驗證文字
        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);
            /**** 隨機縮放文字并將文字旋轉(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;
    }

    // 給定范圍獲得隨機顏色
    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">
     * 驗證碼圖片封裝
     * </p>
     *
     *
     */
    public static class ValidatorCode {
        private BufferedImage image ;
        private String code ;

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

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

新增UsernamePasswordCredentialWithAuthCode類赋秀,繼承UsernamePasswordCredential,添加了驗證碼參數(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{

    /**
     * 帶驗證碼的登錄界面
     */
    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;
    }

    @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猎莲,添加了驗證碼校驗

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新增驗證碼身笤,代碼如下:
<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)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市葵陵,隨后出現(xiàn)的幾起案子液荸,更是在濱河造成了極大的恐慌,老刑警劉巖脱篙,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件娇钱,死亡現(xiàn)場離奇詭異,居然都是意外死亡绊困,警方通過查閱死者的電腦和手機文搂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來秤朗,“玉大人煤蹭,你說我怎么就攤上這事。” “怎么了硝皂?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵常挚,是天一觀的道長。 經(jīng)常有香客問我稽物,道長待侵,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任姨裸,我火速辦了婚禮,結(jié)果婚禮上怨酝,老公的妹妹穿的比我還像新娘傀缩。我一直安慰自己,他們只是感情好农猬,可當我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布赡艰。 她就那樣靜靜地躺著,像睡著了一般斤葱。 火紅的嫁衣襯著肌膚如雪慷垮。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天揍堕,我揣著相機與錄音料身,去河邊找鬼。 笑死衩茸,一個胖子當著我的面吹牛芹血,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播楞慈,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼幔烛,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了囊蓝?” 一聲冷哼從身側(cè)響起饿悬,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎聚霜,沒想到半個月后狡恬,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡俯萎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年傲宜,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片夫啊。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡函卒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情报嵌,我是刑警寧澤虱咧,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站锚国,受9級特大地震影響腕巡,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜血筑,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一绘沉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧豺总,春花似錦车伞、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至表伦,卻和暖如春谦去,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蹦哼。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工鳄哭, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人翔怎。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓窃诉,卻偏偏與公主長得像,于是被迫代替她去往敵國和親赤套。 傳聞我的和親對象是個殘疾皇子飘痛,可洞房花燭夜當晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容

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