天天看點

shiro session與驗證碼

會話管理器

<!-- 會話管理器 -->
  <bean id ="sessionManager" class ="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    <property name="globalSessionTimeout" value ="600000"/>
    <property name ="deleteInvalidSessions" value ="true"/>
  </bean>
           
<!-- securityManager -->
    <bean id ="securityManager" class ="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name ="realm" ref ="customRealm" />
        <property name ="cacheManager" ref ="cacheManager" />
        <property name ="sessionManager" ref ="sessionManager"/>
    </bean>
           

驗證碼

自定義CustomFormAuthenticationFilter
/**
*
* <p>Title:CustomFormAuthenticationFilter</p>
* <p>Description:自定義CustomFormAuthenticationFilter,認證之前實作驗證碼校驗</p>
* <p>PersonWeb:www.xuxiaonan.cn</p>
* @author   dinggc
* @date     2018年4月25日下午3:09:05
* @version  1.0
*/
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter{
    //原FormAuthenticationFilter的認證方法
    @Override
    protected boolean onAccessDenied(ServletRequest request,ServletResponse response)throws Exception{
        //在這裡驗證碼的校驗

        //從session擷取正确的驗證碼
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpSession session = httpServletRequest.getSession();
        String validateCode =(String) httpServletRequest.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);        
        //取出頁面的驗證碼
        //輸入的驗證和session中的驗證進行對比
        String randomcode = httpServletRequest.getParameter("yzm");
        if(randomcode!=null && validateCode!=null &&!randomcode.equals(validateCode)) {
            httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError");
            return true;
        }
        return super.onAccessDenied(request, response);

    }
}
           
配置檔案
<!-- 自定義form認證過濾器 -->
  <!-- 基于form表單的身份驗證過濾器,不配置也會注冊過濾器,表單中的使用者賬号,密碼及loginurl将采用預設值,建議配置 -->
  <bean id ="formAuthenticationFilter" class ="shiro.CustomFormAuthenticationFilter">
    <property name ="usernameParam" value ="username"/>
    <property name ="passwordParam" value ="password"/>
  </bean>
           
<property name ="filters">
            <map>
                <entry key ="authc" value-ref ="formAuthenticationFilter"/>
            </map>
        </property>