码迷,mamicode.com
首页 > 其他好文 > 详细

Shiro 结合 kcaptcha实现登录验证

时间:2015-02-09 23:08:04      阅读:4114      评论:0      收藏:0      [点我收藏+]

标签:shiro   security   kcaptcha   

验证码是为了区分人与电脑,防止电脑代替人冲击系统。在伟大的中国人民人工验证的海洋面前,验证码完全不是个事。
不过一般不是特别热门的系统是不会有人雇佣人民海洋来人工识别验证码的,所有我们的系统还是需要加入验证码机制。
在Java Web系统中验证码世界已经很多种的实现,有些很大很复杂,有些没有维护了,有些验证码人也认证不出来。。。比较合适用的就是Jcaptcha和Kcaptcha。

Captcha使用都是很简单的,通过专门的servlet生成图片,把图片的数据保存在session中,最后在处理请求的servlet中验证图片输入是否正常。当然一般都会有很多配置,因为Captcha生成图片需要时间,所有需要谨慎配置。

Kcaptcha与Shiro登录结合使用

1. Web.xml

<servlet>
        <servlet-name>Kaptcha</servlet-name>
        <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>Kaptcha</servlet-name>
        <url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>

2. 登录Jsp

<%
            String error = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
            if(error != null){

                if(error.contains("IncorrectCaptchaException")){
                    out.print("用户输入验证码错误.");
                }
                else{
                    out.print("登录失败,请重试.");
                }
            }
        %>      
<form action="">
    Username: <input type="text" name="username"/> <br/>
   Password: <input type="password" name="password"/>
    <img src="kaptcha.jpg" /> <input type="text" name="kaptcha" value="" />
</form>

3. Shiro登录Filter

a. 扩展登录UsernamePasswordToken,加入kaptcha字段

public class CaptchaAuthenticationToken extends UsernamePasswordToken{  

    private String kaptcha;  

    public CaptchaAuthenticationToken (){}  

    public CaptchaAuthenticationToken (String username, String password,
            boolean rememberMe, String host, String captcha) {
        super(username, password, rememberMe, host);
        this.captcha = captcha;
    } 

    public void setKaptcha(String kaptcha){  
        this.kaptcha= kaptcha;  
    }  

    public String getKaptcha(){  
        return this.kaptcha;  
    }  
  }

b. 扩展formAuthenticationFilter,检验用户输入验证码

public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter {

    private String captchaParam = "kaptcha";

    public String getCaptchaParam() {
        return captchaParam;
    }

    protected String getCaptcha(ServletRequest request) {
        return WebUtils.getCleanParam(request, getCaptchaParam());
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request,
            ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        String captcha = getCaptcha(request);
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
        return new CaptchaAuthenticationToken(username, password, rememberMe,
                host, captcha);
    }

   // 验证码校验
    protected void doCaptchaValidate(HttpServletRequest request, CaptchaAuthenticationToken token) {
        String captcha = (String) request.getSession().getAttribute(ShiroConstant.CAPTCHA_SESSION_KEY);

        if (StringUtil.isEmpty(token.getCaptcha()) || !token.getCaptcha().equalsIgnoreCase(captcha)) {
            /* 定义IncorrectCaptchaException,shiro显示Exception class name作为error信息 */
            throw new IncorrectCaptchaException("验证码错误!");
        }
    }

    /*
      protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
        String className = ae.getClass().getName();
        request.setAttribute(getFailureKeyAttribute(), className);
    }
    */
    // 认证
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        CaptchaAuthenticationToken token = createToken(request, response);

        try {
            doCaptchaValidate((HttpServletRequest) request, token);

            Subject subject = getSubject(request, response);
            subject.login(token);

            return onLoginSuccess(token, subject, request, response);
        } catch (AuthenticationException e) {
            return onLoginFailure(token, e, request, response);
        }
    }
}

c. 增加 IncorrectCaptchaException

public class IncorrectCaptchaException extends AuthenticationException {

  public IncorrectCaptchaException() {
    super();
  }

  public IncorrectCaptchaException(String message, Throwable cause) {
    super(message, cause);
  }

  public IncorrectCaptchaException(String message) {
    super(message);
  }

  public IncorrectCaptchaException(Throwable cause) {
    super(cause);
  }
}

d.修改Shiro配置文件,让/kaptcha.jpg的访问变成匿名

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/login.jsp" />
        <property name="successUrl" value="/" />
        <property name="filters">
            <map>
                <!-- 启用验证码检验 -->
                <entry key="authc" value-ref="captchaFormAuthenticationFilter"/>
            </map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                /kaptcha.jpg = anon
                /styles/** = anon
                /login = authc
                /logout = logout
                /** = user
            </value>
        </property>
    </bean>

Shiro 结合 kcaptcha实现登录验证

标签:shiro   security   kcaptcha   

原文地址:http://blog.csdn.net/cloud_ll/article/details/43610747

(1)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!