cas登录失败N次后出现验证码

最近学习CAS-SERVICE的扩展,发现网上有很多集成验证码功能的。但验证码的输入在一定程度上影响了用户的体验,同时,登录系统没有验证码的加持,又显得安全性没那么高。在这两者之间,做了一个平衡,在用户输错帐号密码N次后,才要求用户输入验证码,这样能够在保护用户账户安全(防止撞库)的前提下,提升用户的体验。废话不多说了。。。撸起袖子好好干!!!

1.为了能够接受验证码,我们继承UsernamePasswordCredential,增加验证码的接收

public class MyUsernamePasswordCredential 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 MyUsernamePasswordCredential that = (MyUsernamePasswordCredential) 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();
    }
}

2.修改login-webflow.xml,增加流程校验

<!--
 <var name="credential" class="com.ucap.igsd.cas.entiy.UsernamePasswordCredential"/>
-->
    
 <var name="credential" class="com.ucap.igsd.cas.entiy.MyUsernamePasswordCredential"/>
 
 
 <!--*****************华丽的分割线**********************-->
 <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>

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

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

3.修改casLoginView.jsp,增加验证码部分

<c:if test="${errorNum>=5}">
    <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.htm?'+Math.random()" width="93" height="30" src="captcha.htm">
                </td>
            </tr>
        </table>
    </section>
</c:if>

4.修改cas-servlet.xml,增加自定义校验器

<!--  <bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"
        p:centralAuthenticationService-ref="centralAuthenticationService"
        p:warnCookieGenerator-ref="warnCookieGenerator"/>-->

    <bean id="authenticationViaFormAction" class="com.ucap.igsd.cas.handler.MyAuthenticationViaFormAction"
          p:centralAuthenticationService-ref="centralAuthenticationService"
          p:warnCookieGenerator-ref="warnCookieGenerator"/>

5.实现MyAuthenticationViaFormAction

public class MyAuthenticationViaFormAction extends AuthenticationViaFormAction {

    public Integer getErrorNum(Credential credential){
        String requestIp = CasConst.errorMap.get(CasConst.CAS_REDIS_PREFIX+credential.getId());
        String errorNumStr = CasConst.errorMap.get(CasConst.CAS_REDIS_PREFIX + requestIp);
        return Integer.parseInt(errorNumStr==null?"0":errorNumStr);
    }

    public final String validatorCode(final RequestContext context,final Credential credentials, final MessageContext messageContext) throws Exception {
        if (credentials instanceof MyUsernamePasswordCredential) {
            final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
            //获取请求IP
            String requestIp = RequestHelper.getRemoteHost(request);
            request.getSession().removeAttribute("errorMsg");
            CasConst.errorMap.put(CasConst.CAS_REDIS_PREFIX + credentials.getId(), requestIp);

            MyUsernamePasswordCredential rmupc = (MyUsernamePasswordCredential) credentials;
            HttpSession session = request.getSession();
            String authcode = (String) session.getAttribute(CasConst.SESSION_KEY_AUTH_CODE);
            Integer errorNum = getErrorNum(credentials);

            if(errorNum>=5){
                session.removeAttribute(CasConst.SESSION_KEY_AUTH_CODE);
                String submitAuthcode = rmupc.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";
            }
        }
        return "success";
    }

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

public class RequestHelper {

    public static String getRemoteHost(javax.servlet.http.HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }
}

6.修改登录校验方法,当登录失败是,累计失败次数(这里我们用到了之前实现的数据库身份校验的实现类UsersAuthenticationHandler)

public class UsersAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {

    private AccountService accountService;

    public UsersAuthenticationHandler() {
    }

    protected final HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException {
        String username = credential.getUsername();
        String password = credential.getPassword();

        if(password == null) {
            this.logger.debug("{} was not found in the map.", username);
            throw new AccountNotFoundException(username + " not found in backing map.");
        }
        else {
            boolean flag = accountService.checkAccount(username, password);
            
            if (!flag) {
                recordErrorNum(credential);
                throw new FailedLoginException();
            }
            else {
                cleanErrorNumCache(credential);
                return this.createHandlerResult(credential, this.principalFactory.createPrincipal(username), (List)null);
            }
        }
    }
    
    /**
    * 当校验成功后,清楚错误次数
    */
    private void cleanErrorNumCache(UsernamePasswordCredential credential) {
        String requestIp = CasConst.errorMap.get(CasConst.CAS_REDIS_PREFIX+credential.getId());
        CasConst.errorMap.put(CasConst.CAS_REDIS_PREFIX + requestIp,"0");
    }
    
    /**
    * 当校验失败时,增加计数
    */
    private void recordErrorNum(UsernamePasswordCredential credential) {
        String requestIp = CasConst.errorMap.get(CasConst.CAS_REDIS_PREFIX+credential.getId());
        String errorNumStr = CasConst.errorMap.get(CasConst.CAS_REDIS_PREFIX + requestIp);
        CasConst.errorMap.put(CasConst.CAS_REDIS_PREFIX + requestIp,Integer.parseInt(errorNumStr==null?"0":errorNumStr)+1+"");
    }

    public AccountService getAccountService() {
        return accountService;
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
}

7.增加自定义登录流程处理器

public class MyLoginFlowUrlHandler extends DefaultFlowUrlHandler {
    private static final Logger logger = LoggerFactory.getLogger(MyLoginFlowUrlHandler.class);

    /** 缓存key前缀 */
    private String flowExecutionKeyParameter = "execution";

    public void setFlowExecutionKeyParameter(String parameterName) {
        this.flowExecutionKeyParameter = parameterName;
    }

    public String getFlowExecutionKey(HttpServletRequest request) {
        System.out.println(request.getQueryString());
        return request.getParameter(this.flowExecutionKeyParameter);
    }

    public int getErrorNum(HttpServletRequest request){
        String requestIp = RequestHelper.getRemoteHost(request);
        String errorNumStr =CasConst.errorMap.get(CasConst.CAS_REDIS_PREFIX + requestIp);
        return  Integer.parseInt(errorNumStr == null ? "0" : errorNumStr);
    }

    /**
     * Description
     * @param flowId
     * @param flowExecutionKey
     * @param request
     * @return
     * @see org.springframework.webflow.context.servlet.DefaultFlowUrlHandler#createFlowExecutionUrl(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest)
     */
    public String createFlowExecutionUrl(String flowId,String flowExecutionKey, HttpServletRequest request) {
        //设置session更新属性  给出系统当前时间   保证 execution 值更新
        request.getSession().setAttribute("session_flag", System.currentTimeMillis());
        request.getSession().setAttribute("errorNum", getErrorNum(request));
        StringBuilder builder = new StringBuilder();
        builder.append(request.getRequestURI());
        builder.append("?");
        final Map<String, Object> flowParams = new LinkedHashMap<String, Object>(request.getParameterMap());
        flowParams.put(this.flowExecutionKeyParameter, flowExecutionKey);
        appendQueryParameters(builder, flowParams, getEncodingScheme(request));
        return builder.toString();
    }

    public String createFlowDefinitionUrl(String flowId, AttributeMap input,HttpServletRequest request) {
        return new StringBuilder().append(request.getRequestURI())
                .append(request.getQueryString() != null ? new StringBuilder()
                        .append("?").append(request.getQueryString())
                        .toString() : "").toString();
    }

}

修改cas-servlet.xml 注入自定义登录流程处理器

<!--<bean id="loginFlowUrlHandler" class="org.jasig.cas.web.flow.CasDefaultFlowUrlHandler" />-->

  <bean id="loginFlowUrlHandler" class="com.ucap.igsd.cas.handler.MyLoginFlowUrlHandler" />

8.到此部,7788了。想想还差点什么呢。我们在上面主要实现了登录页面的调整、登录流程webflow的改造、验证码验证这三大部分。对,我们的验证码何来呢。我们可以用网上的插件,也可以自己写。网上一推的,这里我们提供一种实现,也是借鉴网络上的。

public class ValidatorCodeUtil {

    public static ValidatorCode getCode() {
        // 验证码图片的宽度。
        int width = 80;
        // 验证码图片的高度。
        int height = 30;
        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);
    }

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

}

9.有了生成验证码的工具,我们需要写一个可供访问的controller来显示到页面上去

public class CaptchaImageCreateController implements Controller,InitializingBean {

    @Override
    public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        ValidatorCodeUtil.ValidatorCode codeUtil = ValidatorCodeUtil.getCode();
        request.getSession().setAttribute(CasConst.SESSION_KEY_AUTH_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 {

    }
}

10.修改cas-servlet.xml(handlerMappingC这个BEAN) 提供验证码访问服务

<bean
  id="handlerMappingC"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
  p:alwaysUseFullPath="true">
<property name="mappings">
  <util:properties>
    <prop key="/serviceValidate">serviceValidateController</prop>
    <prop key="/proxyValidate">proxyValidateController</prop>

    <!--
    <prop key="/samlValidate">samlValidateController</prop>
    -->

    <prop key="/p3/serviceValidate">v3ServiceValidateController</prop>
    <prop key="/p3/proxyValidate">v3ProxyValidateController</prop>
    <prop key="/validate">legacyValidateController</prop>
    <prop key="/proxy">proxyController</prop>
    <prop key="/captcha.htm">captchaImageCreateController</prop>
    <prop key="/authorizationFailure.html">passThroughController</prop>
  </util:properties>
</property>
<!--
 uncomment this to enable sending PageRequest events.
 <property
   name="interceptors">
   <list>
     <ref bean="pageRequestHandlerInterceptorAdapter" />
   </list>
 </property>
  -->
</bean>


<bean id="captchaImageCreateController" class="com.ucap.igsd.cas.controller.CaptchaImageCreateController"/>

11.文中出现过的静态变量

public class CasConst {
    public static ConcurrentHashMap<String,String> errorMap = new ConcurrentHashMap<String,String>();
    public static final String SESSION_KEY_AUTH_CODE="session_key_auth_code";
    public static final String CAS_REDIS_PREFIX = "cas_redis:";

    public static String CAS_REQUIRED_AUTHCODE="required.authcode";
    public static String CAS_ERROR_AUTHCODE_BAD="error.authentication.authcode.bad";

}

12.修改国际化的提示信息 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

至此应该就能呈现出登录失败N次后出现验证码的效果。

上述方法仅仅为实现案例,比较简单,若需要更高级的实现,自行参考实现吧!

声明:方法是基于cas4.1.1 实现的,以上方法有一定程序上参考互联网上的资源来进行实现的。

转载于:https://my.oschina.net/u/1412897/blog/1560440

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值