基於Maven+SSM整合shiro+Redis實現後臺管理項目

本項目由賣鹹魚叔叔開發完成,歡迎大神指點,慎重抄襲!參考了sojson提供的demo,和官方文檔介紹。完整實現了用戶、角色、權限CRUD及分頁,還有shiro的登陸認證+受權訪問控制。css

項目架構:Maven + SpringMVC + Spring + Mybatis + Shiro + Redis
數據庫:MySql前端

前端框架:H-uijava

 

首先建立Maven項目node

1.pom.xml 加入依賴包mysql

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sys</groupId>
  <artifactId>sys</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>sys Maven Webapp</name>
  <url>http://maven.apache.org</url>

        <dependencies>
            <!-- spring依賴管理 -->
            <!-- spring-context 是使用spring的最基本的環境支持依賴,會傳遞依賴core、beans、expression、aop等基本組件,以及commons-logging、aopalliance -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>
            
            <!-- spring-context-support 提供了對其餘第三方庫的內置支持,如quartz等 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>
            
            <!-- spring-orm 是spring處理對象關係映射的組件,傳遞依賴了jdbc、tx等數據庫操做有關的組件 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>
            
            <!-- spring-webmvc 是spring處理前端mvc表現層的組件,也便是springMVC,傳遞依賴了web等web操做有關的組件 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>
            
            <!-- spring-aspects 增長了spring對面向切面編程的支持,傳遞依賴了aspectjweaver -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>
            
            
            <!-- json解析, springMVC 須要用到 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.6.0</version>
            </dependency>
            
            <!-- mybatis依賴管理 -->
            <!-- mybatis依賴 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.3.0</version>
            </dependency>
            
            <!-- mybatis和spring整合 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.2.3</version>
            </dependency>
            
            <!-- mybatis 分頁插件 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>4.1.6</version>
            </dependency>
            
            <!-- mysql驅動包依賴 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.37</version>
            </dependency>
            
            <!-- c3p0依賴 -->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5</version>
            </dependency>
            
            <!-- redis java客戶端jar包 -->
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
            </dependency>
            
            <!-- 文件上傳 -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>
            
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.5</version>
            </dependency>
            
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-email</artifactId>
                <version>1.4</version>
            </dependency>
            
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
                <version>2.7</version>
            </dependency>
            
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.2</version>
            </dependency>
            
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>4.4.4</version>
            </dependency>
            
            
            <!-- junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
            </dependency>
            
            <!-- servlet依賴 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
                <scope>provided</scope>
            </dependency>
            <!-- jsp依賴 -->
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
                <scope>provided</scope>
            </dependency>
            <!-- jstl依賴 -->
            <dependency>
                <groupId>org.glassfish.web</groupId>
                <artifactId>jstl-impl</artifactId>
                <version>1.2</version>
                <exclusions>
                    <exclusion>
                        <groupId>javax.servlet</groupId>
                        <artifactId>servlet-api</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>javax.servlet.jsp</groupId>
                        <artifactId>jsp-api</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            
            
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>   

            
        <!-- shiro依賴包 --> 
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-core</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-spring</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-cas</artifactId>  
            <version>1.2.3</version>  
            <exclusions>  
                <exclusion>  
                    <groupId>commons-logging</groupId>  
                    <artifactId>commons-logging</artifactId>  
                </exclusion>  
            </exclusions>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-web</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-ehcache</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-quartz</artifactId>  
            <version>1.2.3</version>  
        </dependency> 
        <!-- shiro end -->             
            
     
        </dependencies>
    
     <build>
        <finalName>sys</finalName>
        <plugins>
            <!-- 指定JDK編譯版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>  
                <configuration>  
                  <source>1.8</source>
                  <target>1.8</target>
                </configuration> 
            </plugin>
        </plugins>
    </build>

</project>

2.SSM框架配置git

beans.xmlgithub

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd  
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd 
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd 
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <!-- 數據庫鏈接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>  
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sys_test?characterEncoding=UTF8&amp;allowMultiQueries=true"/>
        <property name="user" value="root"/>  
        <property name="password" value="root"/>  
        <property name="maxPoolSize" value="100"/>  
        <property name="minPoolSize" value="10"/>  
        <property name="maxIdleTime" value="60"/>  
    </bean>
    
    <!-- mybatis 的 sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
    
    <!-- mybatis mapper接口自動掃描、自動代理 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.sys.mapper" />
    </bean>
    
    <!-- 事務管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 事務傳播行爲 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="page*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="is*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
        </tx:attributes>
    </tx:advice>

    <!-- 織入事務加強功能 -->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.sys.service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
    </aop:config>

     <!-- 配置掃描spring註解(@Component、@Controller、@Service、@Repository)時掃描的包,同時也開啓了spring註解支持 -->
     <!-- 這個地方只須要掃描service包便可,由於controller包由springMVC配置掃描,mapper包由上面的mybatis配置掃描 -->
    <context:component-scan base-package="com.sys.service"></context:component-scan>

    <!-- 開啓spring aop 註解支持,要想aop真正生效,還須要把切面類配置成bean -->
    <aop:aspectj-autoproxy/>

    
     
</beans>                            

dispatcher-servlet.xmlweb

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd  
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd 
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd 
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd">
                        
    <!-- 配置掃描spring註解時掃描的包,同時也開啓了spring註解支持 -->
    <context:component-scan base-package="com.sys" />

    <!-- 開啓springMVC相關注解支持 -->
    <mvc:annotation-driven />
    
    <!-- 開啓spring aop 註解支持 -->
    <aop:aspectj-autoproxy/>
    

    <!-- 約定大於配置:約定視圖頁面的全路徑 = prefix + viewName + suffix -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


    <!-- 文件上傳解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxInMemorySize" value="40960" />
    </bean>
    
    <!-- 資源映射 -->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/skin/" mapping="/skin/**" />
    <mvc:resources location="/lib/" mapping="/lib/**" />

 
</beans>

mybatis-config.xmlredis

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- 使用log4j2做爲日誌實現 -->
        <setting name="logImpl" value="LOG4J2"/>
    </settings>

    <typeAliases>
        <!-- 爲指定包下的pojo類自動起別名 -->
        <package name="com.sys.pojo"/>
    </typeAliases>
    
    <mappers>
        <!-- 自動加載指定包下的映射配置文件 -->
        <package name="com.sys.mapper"/>
    </mappers>

</configuration>

Log4j2.xml 算法

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE xml>
<Configuration status="OFF">
    <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{0} - %msg%n" />
        </Console>
        <RollingFile name="ROLLING" fileName="/logs/ups-manager/log.log"
             filePattern="/logs/log_%d{yyyy-MM-dd}_%i.log">
            <PatternLayout pattern="%d %p %c{1.} [%t] %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy modulate="true" interval="1"/>
                <SizeBasedTriggeringPolicy size="1024 KB"/>
            </Policies>
            <DefaultRolloverStrategy max="100"/>
        </RollingFile>
    </Appenders>
    
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="CONSOLE" />
            <AppenderRef ref="ROLLING"/>
        </Root>
        
        <!-- 控制某些包下的類的日誌級別 -->
        <Logger name="org.mybatis.spring" level="error">
            <AppenderRef ref="CONSOLE"/>
        </Logger>
    </Loggers>
</Configuration>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

    <!-- 初始化spring容器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>  
  
    <!-- 設置post請求編碼和響應編碼 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        <init-param>
            <!-- 爲true時也對響應進行編碼 -->
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!-- 設置爲/*時纔會攔截全部請求,和servlet有點區別,servlet設置爲/*只攔截全部的一級請求,如/xx.do,而不攔截/xx/xx.do;servlet設置爲/時纔會攔截全部請求 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:spring-shiro.xml,
            classpath:beans.xml,
            classpath:dispatcher-servlet.xml
        </param-value>
    </context-param>
    
  
    <!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    
      <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>  
 
  
    <!-- 初始化springMVC容器 -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
  
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    
</web-app>

3.實現用戶、角色、權限頁面操做功能,這裏就不貼代碼了

4.接下來就是shiro,登陸認證和受權只須要繼承AuthorizingRealm,其繼承了 AuthenticatingRealm(即身份驗證),並且也間接繼承了 CachingRealm(帶有緩存實現)。身份認證重寫doGetAuthenticationInfo方法,受權重寫doGetAuthorizationInfo方法。

Shiro 默認提供的 Realm

 

身份認證流程

 

流程以下:

  1. 首先調用 Subject.login(token) 進行登陸,其會自動委託給 Security Manager,調用以前必須經過 SecurityUtils.setSecurityManager() 設置;
  2. SecurityManager 負責真正的身份驗證邏輯;它會委託給 Authenticator 進行身份驗證;
  3. Authenticator 纔是真正的身份驗證者,Shiro API 中核心的身份認證入口點,此處能夠自定義插入本身的實現;
  4. Authenticator 可能會委託給相應的 AuthenticationStrategy 進行多 Realm 身份驗證,默認 ModularRealmAuthenticator 會調用 AuthenticationStrategy 進行多 Realm 身份驗證;
  5. Authenticator 會把相應的 token 傳入 Realm,從 Realm 獲取身份驗證信息,若是沒有返回 / 拋出異常表示身份驗證失敗了。此處能夠配置多個 Realm,將按照相應的順序及策略進行訪問。

 代碼實現:

/**
 * 
 */
package com.sys.shiro;


import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import com.sys.pojo.AdminUser;
import com.sys.service.AdminUserService;

/**  
* @ClassName: MyRealm  
* @Description: shiro 認證 + 受權   重寫 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    AdminUserService adminUserService;
    
    
    /* (non-Javadoc)
     * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
     */
    /**
     * 受權Realm
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String account = (String)principals.getPrimaryPrincipal();
        AdminUser pojo = new AdminUser();
        pojo.setAccount(account);
        Long userId = adminUserService.selectOne(pojo).getId();
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        /**根據用戶ID查詢角色(role),放入到Authorization裏.*/
        info.setRoles(adminUserService.findRoleByUserId(userId));
        /**根據用戶ID查詢權限(permission),放入到Authorization裏.*/
        info.setStringPermissions(adminUserService.findPermissionByUserId(userId));
        return info; 
    }

    /* (non-Javadoc)
     * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
     */
    /**
     * 登陸認證Realm
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        String username = (String)token.getPrincipal();
        String password = new String((char[])token.getCredentials());
        AdminUser user = adminUserService.login(username, password);
        if(null==user){
            throw new AccountException("賬號或密碼不正確!");
        }
        if(user.getIsDisabled()){
            throw new DisabledAccountException("賬號已經禁止登陸!");
        }
        //**密碼加鹽**交給AuthenticatingRealm使用CredentialsMatcher進行密碼匹配
        return new SimpleAuthenticationInfo(user.getAccount(),user.getPassword(),ByteSource.Util.bytes("3.14159"), getName());
    }

    
    /**
     * 清空當前用戶權限信息
     */
    public  void clearCachedAuthorizationInfo() {
        PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
    /**
     * 指定principalCollection 清除
     */
    public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
    
    
}

shiro的配置:

spring-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!--shiro 核心安全接口  -->
        <property name="securityManager" ref="securityManager"></property>
        <!--登陸時的鏈接  -->
        <property name="loginUrl" value="/login"></property>       
        <!--未受權時跳轉的鏈接  -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
           <!-- 其餘過濾器 -->
           <property name="filters">
               <map>
                   <!-- <entry key="rememberMe" value-ref="RememberMeFilter"></entry> -->
                   <entry key="kickout" value-ref="KickoutSessionControlFilter"/>
               </map>
           </property>
               
        <!-- 讀取初始自定義權限內容-->
        <!-- 若是使用authc驗證,需重寫實現rememberMe的過濾器,或配置formAuthenticationFilter的Bean -->
        <property name="filterChainDefinitions">
            <value>
                /js/**=anon
                /css/**=anon
                /images/**=anon
                /skin/**=anon
                   /lib/**=anon
                   /nodel/**=anon
                   /WEB-INF/jsp/**=anon
                   /adminUserLogin/**=anon
                   
       
                   
                   /**/submitLogin.do=anon
                /**=user,kickout
            </value>
        </property>
    </bean>
    
    
    
    
    <!-- Shiro生命週期處理器-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    
    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="MyRealm"/>
        <property name="rememberMeManager" ref="rememberMeManager"/>
    </bean>
    
    <bean id="MyRealm" class="com.sys.shiro.MyRealm" >
        <property name="cachingEnabled" value="false"/>
    </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>
    
    <!-- sessionIdCookie:maxAge=-1表示瀏覽器關閉時失效此Cookie -->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  
        <constructor-arg value="rememberMe"/>  
        <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"/>
        <!-- 配置存儲rememberMe Cookie的domain爲 一級域名        這裏若是配置須要和Session回話一致更好。-->
        <property name="maxAge" value="604800"/><!-- 記住我==保留Cookie有效7天 -->
    </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('3AvVhmFLUs0KTA3Kprsdag==')}"/>
        <property name="cookie" ref="rememberMeCookie"/>
    </bean>
    
    <!-- 記住我功能設置session的Filter -->
    <bean id="RememberMeFilter" class="com.sys.shiro.RememberMeFilter" />
    
    <!-- rememberMeParam請求參數是 boolean 類型,true 表示 rememberMe -->
    <!-- shiro規定記住我功能最多得user級別的,不能到authc級別.因此若是使用authc,需打開此配置或重寫實現rememberMe的過濾器 -->
    <!-- <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
        <property name="rememberMeParam" value="rememberMe"/>
    </bean> -->    
    
    <bean id="KickoutSessionControlFilter" class="com.sys.shiro.KickoutSessionControlFilter">
    </bean>
               
    
</beans>

5.登陸即密碼失敗屢次後鎖定

/**
 * 
 */
package com.sys.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sys.pojo.AdminUser;
import com.sys.service.AdminUserService;
import com.sys.common.JedisUtils;
import com.sys.shiro.ShiroUtils;


/**  
* @ClassName: LoginController  
* @Description: 登陸
*/
@Controller
public class LoginController{
    protected final static Logger logger = LogManager.getLogger(LoginController.class);
    protected Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    
    @Resource
    AdminUserService adminUserService;
    
    /**
    * @Description: 登陸認證
    * @param um 登陸帳號
    * @param pw 登陸密碼
    * @param rememberMe 記住我
    * @param request
    * @return
    * @throws  
    * @author lao
    * @Date 2018年1月15日下午12:24:19
    * @version 1.00
     */
    @RequestMapping(value="/submitLogin.do",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> submitLogin(String um,String pw,boolean rememberMe,HttpServletRequest request){        
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(um,ShiroUtils.getStrByMD5(pw));                     
        try{           
            token.setRememberMe(rememberMe);
            subject.login(token);
            JedisUtils.del(um);
            logger.info("------------------身份認證成功-------------------");
            resultMap.put("status", 200);
            resultMap.put("message", "登陸成功!");
        } catch (DisabledAccountException dax) {  
            logger.info("用戶名爲:" + um + " 用戶已經被禁用!");
            resultMap.put("status", 500);
            resultMap.put("message", "賬號已被禁用!");
        } catch (ExcessiveAttemptsException eae) {  
            logger.info("用戶名爲:" + um + " 用戶登陸次數過多,有暴力破解的嫌疑!");
            resultMap.put("status", 500);
            resultMap.put("message", "登陸次數過多!");
        } catch (AccountException ae) {  
            logger.info("用戶名爲:" + token.getPrincipal() + " 賬號或密碼錯誤!");
            String excessiveInfo = ExcessiveAttemptsInfo(um);
            if(null!=excessiveInfo){
                resultMap.put("status", 500);
                resultMap.put("message", excessiveInfo);
            }else{
                resultMap.put("status", 500);
                resultMap.put("message", "賬號或密碼錯誤!");
            }
        } catch (AuthenticationException ae) {  
            logger.error(ae);
            logger.info("------------------身份認證失敗-------------------");
            resultMap.put("status", 500);
            resultMap.put("message", "身份認證失敗!");
        } catch (Exception e) { 
            logger.error(e);
            logger.info("未知異常信息。。。。");  
            resultMap.put("status", 500);
            resultMap.put("message", "登陸認證錯誤!");
        }
        return resultMap;
    }
    
    
    /**
    * @Description: 退出
    * @return
    * @throws  
    * @author lao
    * @Date 2018年1月11日下午4:23:35
    * @version 1.00
     */
    @RequestMapping(value="logout",method=RequestMethod.GET)
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
        } catch (Exception e) {
            logger.error("errorMessage:" + e.getMessage());
        }
        return "redirect:login";
    }
    
    
    /**
    * @Description: 驗證器,增長了登陸次數校驗功能
    * @param um 登陸帳號
    * @throws  
    * @author lao
    * @Date 2018年1月15日下午12:03:18
    * @version 1.00
     */
    public String ExcessiveAttemptsInfo(String account){
        String excessiveInfo = null;
        StringBuffer userName = new StringBuffer(account);
        userName.append("ExcessiveCount");
        String accountKey = userName.toString();
        
        if(null == JedisUtils.get(accountKey)){
            JedisUtils.setex(accountKey, 1800, "1");
        }else{
            int count = Integer.parseInt(JedisUtils.get(accountKey))+1;
            JedisUtils.setex(accountKey, 1800-(120*count), Integer.toString(count));
        }
        /**登陸錯誤5次,發出警告*/
        if(Integer.parseInt(JedisUtils.get(accountKey))==5){
            excessiveInfo = "帳號密碼錯誤5次,再錯5次帳號將被禁用!";
        }
        /**登陸錯誤10次,該帳號將被禁用*/
        if(Integer.parseInt(JedisUtils.get(accountKey))==10){
            AdminUser pojo = new AdminUser();
            pojo.setAccount(account);
            AdminUser au = adminUserService.selectOne(pojo);
            if(null!=au){
                adminUserService.updateDisabled(au.getId(), true);
            }
            JedisUtils.del(account);
            excessiveInfo = "帳號密碼錯誤過多,帳號已被禁用!";
        }
        return excessiveInfo;
    }
    
}

6.併發登陸控制

/**
 * 
 */
package com.sys.shiro;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.sys.common.JedisUtils;



/**  
* @ClassName: KickoutSessionControlFilter  
* @Description: 併發登陸控制過濾器
* @author lao  
* @date 2018年1月15日下午2:54:42  
* @version 1.00 
*/
public class KickoutSessionControlFilter extends AccessControlFilter {

    protected final static Logger logger = LogManager.getLogger(KickoutSessionControlFilter.class);
    //踢出狀態,true標示踢出
    final static String KICKOUT_STATUS = KickoutSessionControlFilter.class.getCanonicalName()+ "_kickout_status";    
    
    @Override
    protected boolean isAccessAllowed(ServletRequest request,
            ServletResponse response, Object mappedValue) throws Exception {
        
        HttpServletRequest httpRequest = ((HttpServletRequest)request);
        String url = httpRequest.getRequestURI();
        Subject subject = getSubject(request, response);
        //若是是相關目錄 or 若是沒有登陸 就直接return true
        if(url.startsWith("/open/") || (!subject.isAuthenticated() && !subject.isRemembered())){
            return Boolean.TRUE;
        }
        Session session = subject.getSession();
        Serializable sessionId = session.getId();
        /**
         * 判斷是否已經踢出
         * 1.若是是Ajax 訪問,那麼給予json返回值提示。
         * 2.若是是普通請求,直接跳轉到登陸頁
         */
        Boolean marker = (Boolean)session.getAttribute(KICKOUT_STATUS);
        if (null != marker && marker ) {
            Map<String, String> resultMap = new HashMap<String, String>();
            //判斷是否是Ajax請求
            if (ShiroUtils.isAjax(request) ) {
                logger.debug("當前用戶已經在其餘地方登陸,而且是Ajax請求!");
                resultMap.put("user_status", "300");
                resultMap.put("message", "您已經在其餘地方登陸,請從新登陸!");
                ShiroUtils.out(response, resultMap);
            }
            return  Boolean.FALSE;
        }
        
        
        
        //獲取用戶帳號
        String userName = (String)subject.getPrincipal();
        
        //從緩存獲取用戶-Session信息 <userName,SessionId>
        String jedisSessionId = JedisUtils.get(userName);
        
        //若是已經包含當前Session,而且是同一個用戶,跳過。
        if(null!=jedisSessionId && jedisSessionId.equals((String)sessionId)){
            //更新存儲到緩存1個小時(這個時間最好和session的有效期一致或者大於session的有效期)
            JedisUtils.setex(userName,3600, (String)sessionId);
            return Boolean.TRUE;
        }
        //若是用戶相同,Session不相同,那麼就要處理了
        /**
         * 若是用戶Id相同,Session不相同
         * 1.獲取到原來的session,而且標記爲踢出。
         * 2.繼續走
         */
        if(null!=jedisSessionId && !jedisSessionId.equals((String)sessionId)){
            //標記session已經踢出
            session.setAttribute(KICKOUT_STATUS, Boolean.TRUE);
            //存儲到緩存1個小時(這個時間最好和session的有效期一致或者大於session的有效期)
            JedisUtils.setex(userName, 3600, (String)sessionId);
            return  Boolean.TRUE;
        }
        
        if(null==jedisSessionId){
            //存儲到緩存1個小時(這個時間最好和session的有效期一致或者大於session的有效期)
            JedisUtils.setex(userName, 3600, (String)sessionId);
        }
        return Boolean.TRUE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request,
            ServletResponse response) throws Exception {
        
        //先退出,這一步纔是正常清除Session
        Subject subject = getSubject(request, response);
        subject.logout();
        WebUtils.getSavedRequest(request);
        //再重定向
        WebUtils.issueRedirect(request, response,"/login");
        return false;
    }    
    
    
    
}

以上爲核心代碼只作參考,可自行下載項目部署運行。運行前請確認好環境,並根據resources/readme.rd文檔介紹操做

若有缺陷,大神勿噴,歡迎留言指點!

項目下載連接:https://pan.baidu.com/s/1c2VtyjI

Redis 下載:https://pan.baidu.com/s/1kWRX7Rh

解壓後直接運行 redis-server.exe 啓動服務便可。

相關文章
相關標籤/搜索