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

        // 创建一个随机数生成器类。
        Random random = new Random();

        // 设定图像背景色(因为是做背景,所以偏淡)
        g.setColor(Color. WHITE);
        g.fillRect(0, 0, width, height);
        // 创建字体,字体的大小应该根据图片的高度来定。
        Font font = new Font("", Font.HANGING_BASELINE, 28);
        // 设置字体。
        g.setFont(font);

        // 画边框。
        g.setColor(Color. BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        // 随机产生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用于保存随机产生的验证码,以便用户登录后进行验证。
        StringBuffer randomCode = new StringBuffer();

        // 设置默认生成4个验证码
        int length = 4;
        // 设置备选验证码:包括"a-z"和数字"0-9"
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ;

        int size = base.length();

        // 随机产生4位数字的验证码。
        for (int i = 0; i < length; i++) {
            // 得到随机产生的验证码数字。
            int start = random.nextInt(size);
            String strRand = base.substring(start, start + 1);

            // 用随机产生的颜色将验证码绘制到图像中。
            // 生成随机颜色(因为是做前景,所以偏深)
            // g.setColor(getRandColor(1, 100));

            // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
            g.setColor( new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(strRand, 15 * i + 6, 24);

            // 将产生的四个随机数组合在一起。
            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); // 创建BufferedImage类的对象
        Graphics g = image.getGraphics(); // 创建Graphics类的对象
        Graphics2D g2d = (Graphics2D) g; // 通过Graphics类的对象创建一个Graphics2D类的对象
        Random random = new Random(); // 实例化一个Random对象
        Font mFont = new Font("华文宋体", Font.BOLD, 30); // 通过Font构造字体
        g.setColor(getRandColor(200, 250)); // 改变图形的当前颜色为随机生成的颜色
        g.fillRect(0, 0, width, height); // 绘制一个填色矩形

        // 画一条折线
        BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_BEVEL); // 创建一个供画笔选择线条粗细的对象
        g2d.setStroke(bs); // 改变线条的粗细
        g.setColor(Color.DARK_GRAY); // 设置当前颜色为预定义颜色中的深灰色
        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的数字
            }
            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);
            /**** 随机缩放文字并将文字旋转指定角度 **/
            // 将文字旋转指定角度
            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);
    }

    /**
     *
     * 

* 验证码图片封装 *

* * */ public static class ValidatorCode { private BufferedImage image ; private String code ; /** *

* 图片流 *

* * @return */ public BufferedImage getImage() { return image ; } /** *

* 验证码 *

* * @return */ public String getCode() { return code ; } } }

新增UsernamePasswordCredentialWithAuthCode类,继承UsernamePasswordCredential,添加了验证码参数

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新增图片获取


    cas
    /captcha.jpg

applicationContext.xml

  • 新增bean说明

  • 在handlerMappingC中添加/captcha.jpg映射,captchaImageCreateController,具体内容如下:

    
        
            passThroughController
            pingController
            threadsController
            metricsController
            healthController
            captchaImageCreateController
        
    

login-webflow.xml修改

  • 修改credential属性,修改为新增的UsernamePasswordCredentialWithAuthCode,具体如下:

  • 在viewLoginForm的binder中新增authcode参数,并新增一个transition步骤,具体如下:

    
        
        
        

        
    
    
        

        
    
    

    

  • 新增的步骤具体如下:

    
    
    

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新增验证码,代码如下:
![](captcha.jpg?)

你可能感兴趣的:(cas4.2.7新增验证码校验)