shrio+SpringMVC 登录验证失败,求解了,各位大神.....

咖啡加糖 发布于 2017/01/06 09:59
阅读 336
收藏 1

抛出的异常是:

  try {  
            user.login(token);  
            return new ModelAndView("redirect:/platform/index/index");
        }catch (IncorrectCredentialsException e) {  
        errorMessage = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";  
            System.out.println(errorMessage);  
        } catch (ExcessiveAttemptsException e) {  
        errorMessage = "登录失败次数过多";  
            System.out.println(errorMessage);  
        } catch (LockedAccountException e) {  
        errorMessage = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";  
            System.out.println(errorMessage);  
        }

经过代码跟踪:

 


整体配置如下:

shrioXML:

<!-- 缓存管理器 -->
<bean id="cacheManager" class="com.XXXshrio.SpringCacheManagerWrapper">
<property name="cacheManager" ref="springCacheManager" />
</bean>


<!-- 凭证匹配器 -->
<bean id="credentialsMatcher" class="com.XXX.shrio.RetryLimitHashedCredentialsMatcher">
<constructor-arg ref="cacheManager" />
<property name="hashAlgorithmName" value="md5" />
<property name="hashIterations" value="2" />
<property name="storedCredentialsHexEncoded" value="true" />
</bean>


<!-- Realm实现 -->
<bean id="userRealm" class="com.XXX.shrio.UserRealm">
<property name="credentialsMatcher" ref="credentialsMatcher" />
<property name="cachingEnabled" value="true" />
<property name="authenticationCachingEnabled" value="true" />
<property name="authenticationCacheName" value="authenticationCache" />
<property name="authorizationCachingEnabled" value="true" />
<property name="authorizationCacheName" value="authorizationCache" />
</bean>


<!-- 会话ID生成器 -->
<bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />


<!-- 会话Cookie模板 -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="sid" />
<property name="httpOnly" value="true" />
<property name="maxAge" value="-1" />
</bean>


<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="rememberMe" />
<property name="httpOnly" value="true" />
<property name="maxAge" value="2592000" /><!-- 30天 -->
</bean>


<!-- rememberMe管理器 -->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位) -->
<property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}" />
<property name="cookie" ref="rememberMeCookie" />
</bean>


<!-- 会话DAO -->
<bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="activeSessionsCacheName" value="shiro-activeSessionCache" />
<property name="sessionIdGenerator" ref="sessionIdGenerator" />
</bean>


<!-- 会话验证调度器 -->
<bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
<property name="sessionValidationInterval" value="1800000" />
<property name="sessionManager" ref="sessionManager" />
</bean>


<!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="globalSessionTimeout" value="3600000" />
<property name="deleteInvalidSessions" value="true" />
<property name="sessionValidationSchedulerEnabled" value="true" />
<property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
<property name="sessionDAO" ref="sessionDAO" />
<property name="sessionIdCookieEnabled" value="true" />
<property name="sessionIdCookie" ref="sessionIdCookie" />
</bean>


<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm" />
<property name="sessionManager" ref="sessionManager" />
<property name="cacheManager" ref="cacheManager" />
<property name="rememberMeManager" ref="rememberMeManager" />
</bean>


<!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean>


<!-- 基于Form表单的身份验证过滤器 -->
<bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
<property name="usernameParam" value="userName" />
<property name="passwordParam" value="password" />
<!-- <property name="rememberMeParam" value="rememberMe"/> -->
<property name="loginUrl" value="/platform/login/toLogin" />
<property name="successUrl" value="/platform/index/index"></property>
</bean>


<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<property name="redirectUrl" value="/platform/login/logOut" />
</bean>


<bean id="sysUserFilter" class="com.XXX.shrio.SysUserFilter" />






<!-- Shiro的Web过滤器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/platform/login/toLogin" />
        <property name="filters">
<util:map>
<entry key="authc" value-ref="formAuthenticationFilter" />
<entry key="sysUser" value-ref="sysUserFilter" />
<entry key="logout" value-ref="logoutFilter" />
</util:map>
</property>
        <property name="filterChainDefinitions">
            <value>
            
            /**/*.js=anon  
                /**/*.img=anon  
                /**/*.css=anon  
                /**/*.png=anon  
                /**/*.gif=anon  
                ........
               
            </value>
        </property>
    </bean>


<!-- Shiro生命周期处理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

controller:

    // 登录后台
@RequestMapping(value="/doLogin")
public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


String loginName = request.getParameter("userName");
String password = request.getParameter("password");
// String code = request.getParameter("code");
AdminEntity temp = new AdminEntity();
temp.setLoginName(loginName);
temp.setPassword(CryptographyUtil.md5(password,temp.getSalt()));
String errorMessage = "";

// SessionUtil.addMemberSession(request, adminEntity, SystemConstants.USER_PLATFORM);
        Subject user = SecurityUtils.getSubject();  
        
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);  
//        token.setRememberMe(true);  
  
        try {  
            user.login(token);  
            return new ModelAndView("redirect:/platform/index/index");
        }catch (IncorrectCredentialsException e) {  
        errorMessage = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";  
            System.out.println(errorMessage);  
        } catch (ExcessiveAttemptsException e) {  
        errorMessage = "登录失败次数过多";  
            System.out.println(errorMessage);  
        } catch (LockedAccountException e) {  
        errorMessage = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";  
            System.out.println(errorMessage);  
        } catch (DisabledAccountException e) {  
        errorMessage = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";  
            System.out.println(errorMessage);  
        } catch (ExpiredCredentialsException e) {  
        errorMessage = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";  
            System.out.println(errorMessage);  
        } catch (UnknownAccountException e) {  
        errorMessage = "帐号不存在. There is no user with username of " + token.getPrincipal();  
            System.out.println(errorMessage);  
        } catch (UnauthorizedException e) {  
        errorMessage = "您没有得到相应的授权!" + e.getMessage();  
            System.out.println(errorMessage);  
        }   
         catch (AuthenticationException e) {  
            errorMessage = "登录失败错误信息:" + e;  
            e.printStackTrace();  
            token.clear();  
        }

userRealm:


 //认证方法 
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
   
   
    //获取基于用户名和密码的令牌  
        //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的  
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;  
        String username = (String)token.getPrincipal();
        AdminEntity user = adminService.findAdminByLoginName(username);
        
        if(user == null) {
            throw new UnknownAccountException();//没找到帐号
        }


        if(user.getStatus() == 0) {
            throw new LockedAccountException(); //帐号已经删除
        }


        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现  
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(  
                user.getLoginName(), //用户名  
                user.getPassword(), //密码  
                getName()  //realm name  
        );  
        return authenticationInfo;
    }


加载中
返回顶部
顶部