Shiro实现验证码认证

来源:互联网 发布:自动整点报时软件 编辑:程序博客网 时间:2024/04/30 11:27

验证码是有效防止暴力破解的一种手段,常用做法是在服务端产生一串随机字符串与当前用户会话关联(我们通常说的放入 Session),然后向终端用户展现一张经过“扰乱”的图片,只有当用户输入的内容与服务端产生的内容相同时才允许进行下一步操作

产生验证码

作为演示,我们选择开源的验证码组件 kaptcha。这样,我们只需要简单配置一个 Servlet,页面通过 IMG 标签就可以展现图形验证码。

[html] view plaincopy
  1. <servlet>  
  2.     <servlet-name>kaptcha</servlet-name>  
  3.     <servlet-class>  
  4.         com.google.code.kaptcha.servlet.KaptchaServlet  
  5.     </servlet-class>  
  6. </servlet>  
  7. <servlet-mapping>  
  8.     <servlet-name>kaptcha</servlet-name>  
  9.     <url-pattern>/images/kaptcha.jpg</url-pattern>  
  10. </servlet-mapping>  


扩展 UsernamePasswordTokenShiro 表单认证,页面提交的用户名密码等信息,用 UsernamePasswordToken 类来接收,很容易想到,要接收页面验证码的输入,我们需要扩展此类:


[java] view plaincopy
  1. package javacommon.shiro;  
  2.   
  3. import org.apache.shiro.authc.UsernamePasswordToken;  
  4.   
  5. public class CaptchaUsernamePasswordToken extends UsernamePasswordToken {  
  6.     //验证码字符串  
  7.     private String captcha;  
  8.   
  9.     public CaptchaUsernamePasswordToken(String username, char[] password,  
  10.             boolean rememberMe, String host, String captcha) {  
  11.         super(username, password, rememberMe, host);  
  12.         this.captcha = captcha;  
  13.     }  
  14.   
  15.     public String getCaptcha() {  
  16.         return captcha;  
  17.     }  
  18.   
  19.     public void setCaptcha(String captcha) {  
  20.         this.captcha = captcha;  
  21.     }  
  22.       
  23. }  

扩展 FormAuthenticationFilter

接下来我们扩展 FormAuthenticationFilter 类

[java] view plaincopy
  1. package javacommon.shiro;  
  2.   
  3. import javax.servlet.ServletRequest;  
  4. import javax.servlet.ServletResponse;  
  5. import javax.servlet.http.HttpServletRequest;  
  6.   
  7. import org.apache.shiro.authc.AuthenticationException;  
  8. import org.apache.shiro.subject.Subject;  
  9. import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;  
  10. import org.apache.shiro.web.util.WebUtils;  
  11. import org.slf4j.Logger;  
  12. import org.slf4j.LoggerFactory;  
  13.   
  14. public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter {  
  15.     private static final Logger LOG = LoggerFactory.getLogger(CaptchaFormAuthenticationFilter.class);  
  16.       
  17.     public CaptchaFormAuthenticationFilter() {  
  18.     }  
  19.     @Override  
  20.     /** 
  21.      * 登录验证 
  22.      */  
  23.     protected boolean executeLogin(ServletRequest request,  
  24.             ServletResponse response) throws Exception {  
  25.         CaptchaUsernamePasswordToken token = createToken(request, response);  
  26.         try {  
  27.             /*图形验证码验证*/  
  28.             doCaptchaValidate((HttpServletRequest) request, token);  
  29.             Subject subject = getSubject(request, response);  
  30.             subject.login(token);//正常验证  
  31.             LOG.info(token.getUsername()+"登录成功");  
  32.             return onLoginSuccess(token, subject, request, response);  
  33.         }catch (AuthenticationException e) {  
  34.             LOG.info(token.getUsername()+"登录失败--"+e);  
  35.             return onLoginFailure(token, e, request, response);  
  36.         }  
  37.     }  
  38.   
  39.     // 验证码校验  
  40.     protected void doCaptchaValidate(HttpServletRequest request,  
  41.             CaptchaUsernamePasswordToken token) {  
  42. //session中的图形码字符串  
  43.         String captcha = (String) request.getSession().getAttribute(  
  44.                 com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);  
  45. //比对  
  46.         if (captcha != null && !captcha.equalsIgnoreCase(token.getCaptcha())) {  
  47.             throw new IncorrectCaptchaException("验证码错误!");  
  48.         }  
  49.     }  
  50.   
  51.     @Override  
  52.     protected CaptchaUsernamePasswordToken createToken(ServletRequest request,  
  53.             ServletResponse response) {  
  54.         String username = getUsername(request);  
  55.         String password = getPassword(request);  
  56.         String captcha = getCaptcha(request);  
  57.         boolean rememberMe = isRememberMe(request);  
  58.         String host = getHost(request);  
  59.   
  60.         return new CaptchaUsernamePasswordToken(username,  
  61.                 password.toCharArray(), rememberMe, host, captcha);  
  62.     }  
  63.   
  64.     public static final String DEFAULT_CAPTCHA_PARAM = "captcha";  
  65.   
  66.     private String captchaParam = DEFAULT_CAPTCHA_PARAM;  
  67.   
  68.     public String getCaptchaParam() {  
  69.         return captchaParam;  
  70.     }  
  71.   
  72.     public void setCaptchaParam(String captchaParam) {  
  73.         this.captchaParam = captchaParam;  
  74.     }  
  75.   
  76.     protected String getCaptcha(ServletRequest request) {  
  77.         return WebUtils.getCleanParam(request, getCaptchaParam());  
  78.     }  
  79.       
  80. //保存异常对象到request  
  81.     @Override  
  82.     protected void setFailureAttribute(ServletRequest request,  
  83.             AuthenticationException ae) {  
  84.         request.setAttribute(getFailureKeyAttribute(), ae);  
  85.     }  
  86. }  



前面验证码校验不通过,我们抛出一个异常 IncorrectCaptchaException,此类继承 AuthenticationException,之所以需要扩展一个新的异常类,为的是在页面能更精准显示错误提示信息。


[java] view plaincopy
  1. package javacommon.shiro;  
  2.   
  3. import org.apache.shiro.authc.AuthenticationException;  
  4.   
  5. public class IncorrectCaptchaException extends AuthenticationException {  
  6.   
  7.     public IncorrectCaptchaException() {  
  8.         super();  
  9.     }  
  10.   
  11.     public IncorrectCaptchaException(String message, Throwable cause) {  
  12.         super(message, cause);  
  13.     }  
  14.   
  15.     public IncorrectCaptchaException(String message) {  
  16.         super(message);  
  17.     }  
  18.   
  19.     public IncorrectCaptchaException(Throwable cause) {  
  20.         super(cause);  
  21.     }  
  22. }  

Filter的配置及使用

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  5.         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">  
  6.   
  7.     <!-- Shiro Filter 拦截器相关配置 -->  
  8.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  9.         <!-- securityManager -->  
  10.         <property name="securityManager" ref="securityManager" />  
  11.         <!-- 登录路径 -->  
  12.         <property name="loginUrl" value="/login.jsp" />  
  13.         <!-- 登录成功后跳转路径 -->  
  14.         <property name="successUrl" value="/pages/index.jsp" />  
  15.         <!-- 授权失败跳转路径 -->  
  16.         <property name="unauthorizedUrl" value="/login.jsp" />  
  17.         <property name="filters">  
  18.             <util:map>  
  19.                 <entry key="authc" value-ref="myAuthenFilter" />  
  20.             </util:map>  
  21.         </property>  
  22.         <!-- 过滤链定义 -->  
  23.         <property name="filterChainDefinitions">  
  24.             <value>  
  25.                 /login.jsp = authc  
  26.                 /pages/* = authc  
  27.                 /index.jsp* = authc  
  28.                 /logout.do = logout  
  29.                 <!-- 访问这些路径必须拥有某种权限 /role/edit/* = perms[role:edit] /role/save = perms[role:edit]   
  30.                     /role/list = perms[role:view] -->  
  31.             </value>  
  32.         </property>  
  33.     </bean>  
  34.   
  35.     <!-- 自定义验证拦截器 -->  
  36.     <bean id="myAuthenFilter" class="javacommon.shiro.CaptchaFormAuthenticationFilter" />  
  37.   
  38.     <!-- securityManager -->  
  39.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  40.         <property name="realm" ref="myRealm" />  
  41.     </bean>  
  42.   
  43.     <!-- <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">   
  44.         <property name="cacheManager" ref="cacheManager" /> </bean> -->  
  45.   
  46.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
  47.   
  48.     <!-- 自定义Realm实现 -->  
  49.     <bean id="myRealm" class="javacommon.shiro.CustomRealm">  
  50.         <!-- <property name="cacheManager" ref="shiroCacheManager" /> -->  
  51.     </bean>  
  52. </beans>  

登录页面:


[html] view plaincopy
  1. <%@page import="org.apache.shiro.web.filter.authc.FormAuthenticationFilter"%>  
  2. <%@page import="javacommon.shiro.IncorrectCaptchaException"%>  
  3. <%@page import="org.apache.shiro.authc.AuthenticationException"%>  
  4. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  5.     pageEncoding="UTF-8"%>  
  6. <%  
  7.     String path = request.getContextPath();  
  8.     String basePath = request.getScheme() + "://"  
  9.             + request.getServerName() + ":" + request.getServerPort()  
  10.             + path + "/";  
  11. %>  
  12. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  13. <html>  
  14. <head>  
  15. <base href="<%=basePath%>">  
  16. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  17. <title>Insert title here</title>  
  18. <style type="text/css">  
  19. .error {  
  20.     color: red;  
  21. }  
  22. </style>  
  23. <script type="text/javascript">  
  24. function refreshCaptcha(){  
  25.     document.getElementById("img_captcha").src="<%=basePath%>images/kaptcha.jpg?t=" + Math.random();  
  26. }  
  27. </script>  
  28. </head>  
  29. <body>  
  30.   
  31.     <%  
  32.         Object obj = request  
  33.                 .getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);  
  34.         String msg = "";  
  35.         if (obj != null) {  
  36.             if (obj instanceof IncorrectCaptchaException)  
  37.                 msg = "验证码错误!";  
  38.             else   
  39.                 msg = "账号或密码错误!";  
  40.         }  
  41.           
  42.         out.println("<div class='error'>" + msg + "</div>");  
  43.     %>  
  44.   
  45.     <form action="login.jsp" method="post">  
  46.         <input type="hidden" name="rememberMe" value="true" /> <br />  
  47.         <table>  
  48.   
  49.             <tr>  
  50.                 <td>用户帐号:</td>  
  51.                 <td><input type="text" name="username" id="username" value="" /></td>  
  52.             </tr>  
  53.             <tr>  
  54.                 <td>登录密码:</td>  
  55.                 <td><input type="password" name="password" id="password"  
  56.                     value="" /></td>  
  57.             </tr>  
  58.             <tr>  
  59.                 <td>验证码:</td>  
  60.                 <td><input type="text" name="captcha" /></td>  
  61.             </tr>  
  62.             <tr>  
  63.                 <td> </td>  
  64.                 <td><img alt="验证码" src="images/kaptcha.jpg" title="点击更换"  
  65.                     id="img_captcha" onclick="javascript:refreshCaptcha();">(看不清<a href="javascript:void(0)" onclick="javascript:refreshCaptcha()">换一张</a>)</td>  
  66.             </tr>  
  67.             <tr>  
  68.                 <td colspan="2"><input value="登录" type="submit"></td>  
  69.             </tr>  
  70.         </table>  
  71.   
  72.     </form>  
  73. </body>  
  74. </html>  





转载来自:http://blog.csdn.net/zhengwei223/article/details/9969831
0 0
原创粉丝点击