shiro + springMVC + spring + mybatis (maven 整合)

1.大纲 :
a.编写pom.xml,引入各种依赖包, 以下有模板
b.编写applicationContext.xml文件
c.编写springMVC-servlet.xml文件
d.编写spring-shiro.xml文件
e.编写jdbc.properties文件
f.编写log4j.properties文件
g.编写ehcache-shiro.xml文件(缓存文件配置)
h.编写java文件
i.project结构截图 :
这里写图片描述
(1).编写pom.xml, 主要添加shiro-core.jar, shiro-web.jar, shiro-spring.jar, shiro-ehcache.jar, ehcache-core.jar等依赖包

这里是pom.xml的模板
<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.shiroTest</groupId>
  <artifactId>TestShiro</artifactId>
  <version>0.0.1-SNAPSHOT</version>
 <!-- 打包方式为war包 -->
  <packaging>war</packaging>
  <properties>
    <webVersion>3.0</webVersion>
  </properties>
  <!-- 引入依赖包 -->
  <dependencies>
    <!-- javaee的api -->
      <dependency>
          <groupId>javax</groupId>
          <artifactId>javaee-api</artifactId>
          <version>7.0</version>
          <scope>provided</scope>
      </dependency>
    <!-- spring依赖包 -->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
     <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aspects</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-expression</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-instrument</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-instrument-tomcat</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-orm</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-oxm</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc-portlet</artifactId>
          <version>4.0.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.6.5</version>
      </dependency>

    <!-- c3p0的数据源 -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>5.2.12.Final</version>
    </dependency>

    <!-- 日志依赖包 -->
    <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.25</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.25</version>
      </dependency>

      <!-- commons包 -->
      <dependency>
          <groupId>commons-beanutils</groupId>
          <artifactId>commons-beanutils</artifactId>
          <version>1.9.3</version>
      </dependency>
      <dependency>
          <groupId>commons-collections</groupId>
          <artifactId>commons-collections</artifactId>
          <version>3.2.2</version>
      </dependency>
      <dependency>
          <groupId>commons-lang</groupId>
          <artifactId>commons-lang</artifactId>
          <version>2.6</version>
      </dependency>
      <dependency>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
          <version>1.0.4</version>
      </dependency>
      <dependency>
          <groupId>net.sf.ezmorph</groupId>
          <artifactId>ezmorph</artifactId>
          <version>1.0.6</version>
      </dependency>

    <!-- json依赖包 -->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.37</version>
      </dependency>

    <!-- 数据库驱动依赖包 -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.40</version>
      </dependency>

    <!-- mybatis依赖包 -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.2.2</version>
      </dependency>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.2.0</version>
      </dependency>

    <!-- 加入shrio依赖包 -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-web</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.4.0</version>
    </dependency>
    <!-- 用户存储shiro认证信息缓存的 -->   
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-ehcache</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.6.11</version>
    </dependency>

  </dependencies>

  <build>
  <plugins>
        <!-- 添加Tomcat容器 -->
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <port>8080</port>
                <server>tomcat</server>
                <username>admin</username>
                <password>admin</password>
            </configuration>
        </plugin>
    </plugins>
    <!--这里是打包成war包的时候不用过滤的xml, properties文件, 保证打包之后war包中有这些xml, properties文件-->
    <resources>
           <resource>  
               <directory>${basedir}/src/main/java</directory>  
               <includes>  
                   <!--这里主要是mybatics的mapper.xml-->
                   <include>**/*.xml</include>  
               </includes>  
           </resource>  
            <resource>  
               <directory>${basedir}/src/main/resources</directory>  
               <includes>  
                   <include>**/*.xml</include>  
                   <include>**/*.properties</include>
               </includes>  
           </resource>
    </resources>
  </build>

</project>

(2)编写applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
  xmlns:p="http://www.springframework.org/schema/p"
  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-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.0.xsd">

  <!-- 使用注解式注入 -->
  <context:annotation-config/>

  <!--扫描dao层和service层的包-->
  <context:component-scan base-package="com.shirotest.test.service.impl"/>

  <!-- 加载jdbc配置文件的bean -->
  <bean class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>classpath:jdbc.properties</value>
    </property>
  </bean>

  <!-- 配置数据源 -->
  <bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name = "driverClass" value = "${jdbc.driverClass}"></property>
  <property name = "jdbcUrl" value = "${jdbc.jdbcUrl}"></property>
  <property name = "user" value = "${jdbc.user}"></property>
  <property name = "password" value = "${jdbc.password}"></property>
  <!-- 初始化数据连接池的连接数 -->
  <property name="initialPoolSize" value="${c3p0.initialPoolSize}"></property>
  <!-- 初始化连接最大空闲时间 -->
  <property name="maxIdleTime" value="${c3p0.maxIdleTime}"></property>
  <!-- 初始化连接池的最大连接数 -->
  <property name="maxPoolSize" value="${c3p0.maxPoolSize}"></property>
  <!-- 初始化连接池的最少连接数 -->
  <property name="minPoolSize" value="${c3p0.minPoolSize}"></property>
  </bean>


  <!-- 配置会话工厂 -->
  <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref = "dataSource"/>
      <!-- 自动扫描XXXmapper.xml文件-->
      <property name="mapperLocations" value = "classpath:com/shirotest/mapper/UserinfoMapper.xml"/>
  </bean>

  <!-- 配置映射接口位置 -->
  <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
      <!--扫描mapper下面的所有接口, 创建接口的动态代理-->
      <property name="basePackage" value = "com.shirotest.mapper"/>
      <property name="sqlSessionFactory" ref = "sqlSessionFactory"/>
  </bean>

  <!-- 将DataSource关联到事务管理功能 -->
  <bean id= "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref = "dataSource"/>
  </bean>
  <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

(3)编写springMVC-servlect.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:mvc="http://www.springframework.org/schema/mvc"
  xmlns:p="http://www.springframework.org/schema/p"
  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-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.0.xsd">

  <!-- -->
  <mvc:annotation-driven/>
  <mvc:default-servlet-handler/>

  <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
  <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

  <!--代码扫描ssm.controller包中带有@Controller注解的控制层类-->

  <context:component-scan base-package="com.shirotest.test.controller"/>

  <!--代码对控制层进行事务代理AOP支持-->
  <aop:aspectj-autoproxy proxy-target-class="true"/>

</beans>

(4)编写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:mvc="http://www.springframework.org/schema/mvc"
  xmlns:p="http://www.springframework.org/schema/p"
  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-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 启用shiro授权注解拦截方式 -->
    <bean id = "shiroFilter" class = "org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 装配securityManager -->
        <property name="securityManager" ref = "securityManager"/>
        <!-- 配置登录页面 -->
        <property name="loginUrl" value = "/html/login.html"/>
        <!-- 配置登陆成功后的页面 -->
        <property name="successUrl" value = "/html/success.html"/>
        <!-- 配置未合法的的页面 -->
        <property name="unauthorizedUrl" value = "/html/unauthorized.html"/>
        <!-- 配置哪些页面访问需要拦截 -->
        <property name="filterChainDefinitions">
            <value>
                /html/login.html = anon<!-- 无需认证或者权限 -->
                /html/success.html = anon
                /html/fail.html = anon
                /html/user.html = roles[user]<!-- 必须认证并且是拥有user角色才能访问 -->
                /html/admin.html = roles[admin]<!-- 必须认证并且拥有admin角色才能访问 -->
                /html/logout = logout
            </value>
        </property>
    </bean>

    <!-- 配置缓存管理器 -->
    <bean id = "cacheManager" class = "org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value = "classpath:ehcache-shiro.xml"/>
    </bean>

    <!-- 配置进行授权和认证的Realm, 自己实现的Realm, 亦可以使用官方的Realm, 后续会说明Realm的写法作用 -->
    <bean id = "shiroRealm" class = "com.shirotest.util.ShiroRealm">
        <!--在自定义的Realm中使用自定义的业务逻辑进行认证-->
        <property name="userService" ref = "userService"></property>
    </bean>

    <!-- 配置Shiro的securityManager bean, 核心的安全管理器-->
    <bean id = "securityManager" class = "org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!-- <property name="cacheManager"  ref = "cacheManager"/> -->
        <property name="realm" ref = "shiroRealm"/>
        <property name="sessionMode" value = "native"/>
    </bean>

    <!-- 配置 Bean 后置处理器: 会自动的调用和 Spring 整合后各个组件的生命周期方法 -->
    <bean id = "lifecycleBeanPostProcessor" class = "org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

</beans>

(5)编写jdbc.properties文件

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/testssm?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.user=root
jdbc.password=root
c3p0.initialPoolSize=10
c3p0.maxIdleTime=30
c3p0.maxPoolSize=100
c3p0.minPoolSize=10

(6)编写log4j.properties文件

#输出的登记为INFO, 输出类型是console, 输出的目的地是logfile\
log4j.rootCategory=INFO,console,logfile

#配置控制台的日志
#输出的目的地是控制台
log4j.appender.console=org.apache.log4j.ConsoleAppender
#设置输出时候的端的布局是哪种布局
log4j.appender.console.layout=org.apache.log4j.PatternLayout
#指定输出的具体信息, 以及具体格式
log4j.appender.console.layout.ConversionPattern= %p %d{yyyy-MM-dd HH:mm:ss} - %t - [%c] : %m %n

#配置指定日志打印日志文件
#配置日志文件的路径
log4j.appender.logfile.File=D\:\\Workspaces\\MyEclipse 2017 CI\\.metadata\\.me_tcat85\\logs\\TestShiro_log\\modeltest.log
#配置日志文件每天产生一个
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
#配置日志文件的日期格式
log4j.appender.logfile.DatePattern=.yyyy-MM-dd
#配置日志文件的布局格式
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
# 配置日志文件日志打印的格式
log4j.appender.logfile.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss} - %t - [%c] : %m %n

(7)编写ehcache-shiro.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false"  name="shirocache"> 
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
        />
    <!-- 登录记录缓存 锁定10分钟 -->
    <cache name="passwordRetryCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <cache name="authorizationCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <cache name="authenticationCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <cache name="shiro-activeSessionCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <cache name="shiro_cache"
           maxElementsInMemory="2000"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="0"
           timeToLiveSeconds="0"
           maxElementsOnDisk="0"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="FIFO"
           statistics="true">
    </cache>
</ehcache>

(8)编写java文件(此处关于springMVC + spring + mybatis)的就不细说了, 重点说shiro

a.Controller(用于处理个人信息表单的controller, 同时调用shiro的进行认证授权)

package com.shirotest.test.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@Scope("prototype")
public class LoginController {

    private Log logger = LogFactory.getLog(getClass());
    @RequestMapping("login.spring")
    public String Login(@RequestBody String userString){
    if(SecurityUtils.getSubject().isAuthenticated()){//已经经过认证
        return "/html/success.html";
    }else{//否则进行认证
            UsernamePasswordToken token = new UsernamePasswordToken("124", "124", null);
            token.setRememberMe(true);
            try{
                Subject s = SecurityUtils.getSubject();
                s.login(token);//调用我们在spring-shiro.xml中注册的Realm去进行认证授权
                if(s.isAuthenticated()){
                    logger.info("认证通过了");
                    logger.info("/html/success.html的是否授权 : " + s.isPermitted("/html/success.html"));
                }else{
                    logger.info("认证不通过");
                }
            }catch(UnknownAccountException ex){
                return "/html/login.html";
            }catch(IncorrectCredentialsException ex){
                return "/html/fail.html";
            }catch(AuthenticationException ex){
                return "/html/unauthorized.html";
            }catch(Exception e){
                System.out.println("内部错误");
                return "/html/fail.html";
            }
            return "/html/success.html";
        }

    }

}

b.自定义的Realm

package com.shirotest.util;

import java.util.Arrays;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import com.shirotest.orm.Userinfo;
import com.shirotest.test.service.UserService;

public class ShiroRealm extends AuthorizingRealm{

    private Log logger = LogFactory.getLog(getClass());
    private UserService userService;//在spring-shiro.xml已经有这个bean, 这里不能使用注释的方式注入

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        // TODO Auto-generated method stub
        //将token转换为Userinfo
        Userinfo userinfo = new Userinfo();
        userinfo.setUsername(((UsernamePasswordToken) authcToken).getUsername());
        userinfo.setPassword(Arrays.toString(((UsernamePasswordToken) authcToken).getPassword()));
        //调用自定义的业务逻辑查询数据库验证用户信息
        Userinfo ui = userService.CheckUserinfo(userinfo);
        if(ui == null){
            logger.info("认证验证的用户信息为空");
            return null;//异常处理查不到记录
        }
        //设置session
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("user", ui);
        //当前的 Realm 的name
        String realmName = this.getName();
        //登陆的主要信息, 可以使一个实体类的对象, 但该实体类的对象一定是根据token的username查询得到
        Object principal = authcToken.getPrincipal();
        logger.info("生成Authencication");
        return new SimpleAuthenticationInfo(principal, ui.getPassword(), realmName);//返回根据获取到的密码返回认证信息
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // TODO Auto-generated method stub
        logger.info("进来授权了");
        Userinfo userinfo = (Userinfo)SecurityUtils.getSubject().getSession().getAttribute("user");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        logger.info("授权的角色是 : " + userinfo.getRole());
        info.addRole(userinfo.getRole());
        info.addStringPermission("/html/success.html");
        logger.info("授权了");
        return info;//返回授权信息
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37838381/article/details/78774328