前言:

  Shiro是一个权限、会话管理的开源Java安全框架;Spring Boot集成Shiro后可以方便的使用Session;

工程概述:

(工程结构图)

一、建立Spring Boot工程

  参照http://www.cnblogs.com/liangblog/p/5207855.html 建立一个SpringBoot工程;

二、修改pom.xml,引入所需jar包

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4.  
  5. <groupId>com.ddd</groupId>
  6. <artifactId>programme</artifactId>
  7. <version>0.0.1</version>
  8. <packaging>jar</packaging>
  9.  
  10. <name>programme</name>
  11. <url>http://maven.apache.org</url>
  12. <properties>
  13. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14. </properties>
  15.  
  16. <parent>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-parent</artifactId>
  19. <version>1.4.2.RELEASE</version>
  20. </parent>
  21.  
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27.  
  28. <dependency>
  29. <groupId>junit</groupId>
  30. <artifactId>junit</artifactId>
  31. <scope>test</scope>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.data</groupId>
  35. <artifactId>spring-data-commons</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.data</groupId>
  39. <artifactId>spring-data-jpa</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.springframework.data</groupId>
  43. <artifactId>spring-data-jdbc-core</artifactId>
  44. <version>1.2.1.RELEASE</version>
  45. </dependency>
  46. <dependency>
  47. <groupId>com.fasterxml.jackson.core</groupId>
  48. <artifactId>jackson-core</artifactId>
  49. </dependency>
  50. <dependency>
  51. <groupId>com.fasterxml.jackson.core</groupId>
  52. <artifactId>jackson-annotations</artifactId>
  53. </dependency>
  54. <dependency>
  55. <groupId>com.fasterxml.jackson.core</groupId>
  56. <artifactId>jackson-databind</artifactId>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.slf4j</groupId>
  60. <artifactId>slf4j-api</artifactId>
  61. </dependency>
  62. <dependency>
  63. <groupId>org.apache.httpcomponents</groupId>
  64. <artifactId>httpcore</artifactId>
  65. </dependency>
  66. <dependency>
  67. <groupId>org.apache.httpcomponents</groupId>
  68. <artifactId>httpclient</artifactId>
  69. </dependency>
  70. <dependency>
  71. <groupId>org.apache.httpcomponents</groupId>
  72. <artifactId>httpmime</artifactId>
  73. </dependency>
  74. <dependency>
  75. <groupId>mysql</groupId>
  76. <artifactId>mysql-connector-java</artifactId>
  77. </dependency>
  78. <dependency>
  79. <groupId>org.springframework.boot</groupId>
  80. <artifactId>spring-boot-starter-jdbc</artifactId>
  81. </dependency>
  82.  
  83. <dependency>
  84. <groupId>javax</groupId>
  85. <artifactId>javaee-api</artifactId>
  86. <version>7.0</version>
  87. </dependency>
  88. <dependency>
  89. <groupId>org.apache.shiro</groupId>
  90. <artifactId>shiro-spring</artifactId>
  91. <version>1.2.3</version>
  92. </dependency>
  93. <dependency>
  94. <groupId>org.apache.shiro</groupId>
  95. <artifactId>shiro-cas</artifactId>
  96. <version>1.2.3</version>
  97. </dependency>
  98. <dependency>
  99. <groupId>org.apache.shiro</groupId>
  100. <artifactId>shiro-ehcache</artifactId>
  101. <version>1.2.3</version>
  102. </dependency>
  103. <dependency>
  104. <groupId>org.springframework</groupId>
  105. <artifactId>spring-jdbc</artifactId>
  106. </dependency>
  107. <dependency>
  108. <groupId>org.apache.shiro</groupId>
  109. <artifactId>shiro-core</artifactId>
  110. <version>1.2.3</version>
  111. </dependency>
  112. <dependency>
  113. <groupId>org.apache.shiro</groupId>
  114. <artifactId>shiro-web</artifactId>
  115. <version>1.2.3</version>
  116. </dependency>
  117. <dependency>
  118. <groupId>org.jasig.cas.client</groupId>
  119. <artifactId>cas-client-core</artifactId>
  120. <version>3.4.1</version>
  121. </dependency>
  122. </dependencies>
  123.  
  124. <!-- Package as an executable jar -->
  125. <build>
  126. <defaultGoal>compile</defaultGoal>
  127. <plugins>
  128. <plugin>
  129. <groupId>org.springframework.boot</groupId>
  130. <artifactId>spring-boot-maven-plugin</artifactId>
  131. </plugin>
  132. </plugins>
  133. </build>
  134.  
  135. <!-- Add Spring repositories -->
  136. <!-- (you don't need this if you are using a .RELEASE version) -->
  137. <!--
  138. <repositories>
  139. <repository>
  140. <id>spring-snapshots</id>
  141. <url>http://repo.spring.io/snapshot</url>
  142. <snapshots><enabled>true</enabled></snapshots>
  143. </repository>
  144. <repository>
  145. <id>spring-milestones</id>
  146. <url>http://repo.spring.io/milestone</url>
  147. </repository>
  148. </repositories>
  149. <pluginRepositories>
  150. <pluginRepository>
  151. <id>spring-snapshots</id>
  152. <url>http://repo.spring.io/snapshot</url>
  153. </pluginRepository>
  154. <pluginRepository>
  155. <id>spring-milestones</id>
  156. <url>http://repo.spring.io/milestone</url>
  157. </pluginRepository>
  158. </pluginRepositories>
  159. -->
  160.  
  161. </project>

pom.xml

  主要引入日志、数据库,shrio相关的jar包

三、添加配置文件和日志文件

配置文件需要放到resource文件夹下(指向classpath),并取名aplication.properties,工程会自动查找到文件配置信息

  配置文件:

  1. displayname = pm
  2.  
  3. server.port=8011
  4. server.session.timeout=1000
  5. server.tomcat.uri-encoding=UTF-8
  6.  
  7. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
  8. spring.datasource.username=root
  9. spring.datasource.password=123456
  10. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  11. spring.datasource.max-idle=10
  12. spring.datasource.max-wait=10000
  13. spring.datasource.min-idle=5
  14. spring.datasource.initial-size=5
  15.  
  16. logging.config=classpath:pm-logback.xml
  17. logging.path=log

  日志文件:

  1. <configuration scan="true" scanPeriod="10 seconds">
  2. <include resource="org/springframework/boot/logging/logback/base.xml" />
  3. <!-- 日志的级别:debug,info,warn,error -->
  4. <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  5. <!--
  6. <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
  7. <level>DEBUG</level>
  8. </filter>
  9.  
  10. -->
  11. <File>${LOG_PATH}/info.log</File>
  12. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  13. <fileNamePattern>${LOG_PATH}/pm-info-%d{yyyyMMdd}.log.%i</fileNamePattern>
  14. <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
  15. <maxFileSize>100MB</maxFileSize>
  16. </timeBasedFileNamingAndTriggeringPolicy>
  17. <maxHistory>2</maxHistory>
  18. </rollingPolicy>
  19. <layout class="ch.qos.logback.classic.PatternLayout">
  20. <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n
  21. </Pattern>
  22. </layout>
  23. </appender>
  24.  
  25. <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  26. <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
  27. <level>ERROR</level>
  28. </filter>
  29. <File>${LOG_PATH}/error.log</File>
  30. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  31. <fileNamePattern>${LOG_PATH}/pm-error-%d{yyyyMMdd}.log.%i
  32. </fileNamePattern>
  33. <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
  34. <maxFileSize>100MB</maxFileSize>
  35. </timeBasedFileNamingAndTriggeringPolicy>
  36. <maxHistory>2</maxHistory>
  37. </rollingPolicy>
  38. <layout class="ch.qos.logback.classic.PatternLayout">
  39. <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n
  40.  
  41. </Pattern>
  42. </layout>
  43. </appender>
  44. <root level="INFO">
  45. <appender-ref ref="INFO_FILE" />
  46. <appender-ref ref="ERROR_FILE" />
  47. </root>
  48.  
  49. </configuration>

pm-logback.xml

  部署工程时可以放到工程jar所在文件夹内,部署的工程会自动找到文件;

四、添加Shiro支持功能:

  1、新建shiro配置类,Shiro的主要配置信息都在此文件内实现;

  1. package com.ddd.program.config;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.LinkedHashMap;
  6. import java.util.Map;
  7.  
  8. import org.apache.shiro.cache.ehcache.EhCacheManager;
  9. import org.apache.shiro.mgt.SecurityManager;
  10. import org.apache.shiro.session.SessionListener;
  11. import org.apache.shiro.session.mgt.SessionManager;
  12. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  13. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  14. import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
  15. import org.springframework.context.annotation.Bean;
  16. import org.springframework.context.annotation.Configuration;
  17.  
  18. @Configuration
  19. public class ShiroConfiguration {
  20.  
  21. /**
  22. * ShiroFilterFactoryBean 处理拦截资源文件问题。
  23. * 注意:单独一个ShiroFilterFactoryBean配置是或报错的
  24. * 初始化ShiroFilterFactoryBean的时候需要注入:SecurityManager
  25. */
  26. @Bean
  27. public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
  28. ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  29.  
  30. // 必须设置 SecurityManager
  31. shiroFilterFactoryBean.setSecurityManager(securityManager);
  32.  
  33. // 拦截器.
  34. Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
  35.  
  36. //filterChainDefinitionMap.put("/page/*", "authc");
  37. // 配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了
  38. //filterChainDefinitionMap.put("/security/logoff", "logout");
  39.  
  40. shiroFilterFactoryBean.setLoginUrl("/#/login");
  41. // 未授权界面;
  42. shiroFilterFactoryBean.setUnauthorizedUrl("/403");
  43.  
  44. shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
  45.  
  46. return shiroFilterFactoryBean;
  47. }
  48.  
  49. @Bean
  50. public SecurityManager securityManager() {
  51. DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
  52. MyRealm myRealm = new MyRealm();
  53. securityManager.setRealm(myRealm);
  54. securityManager.setSessionManager(sessionManager());
  55. securityManager.setCacheManager(ehCacheManager());
  56. return securityManager;
  57. }
  58.  
  59. @Bean
  60. public SessionManager sessionManager() {
  61. DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
  62. Collection<SessionListener> listeners = new ArrayList<SessionListener>();
  63. listeners.add(new MySessionListener());
  64. sessionManager.setSessionListeners(listeners);
  65. return sessionManager;
  66. }
  67.  
  68. @Bean
  69. public EhCacheManager ehCacheManager() {
  70. EhCacheManager ehCacheManager = new EhCacheManager();
  71. //ehCacheManager.setCacheManagerConfigFile("classpath:encache.xml");
  72. return ehCacheManager;
  73. }
  74.  
  75. }

  2、新建登录验证和Session监听的类(上面的类所需要的两个类)

    登录相关:

  1. package com.ddd.program.config;
  2.  
  3. import org.apache.shiro.authc.AuthenticationException;
  4. import org.apache.shiro.authc.AuthenticationInfo;
  5. import org.apache.shiro.authc.AuthenticationToken;
  6. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  7. import org.apache.shiro.authc.UnknownAccountException;
  8. import org.apache.shiro.authc.UsernamePasswordToken;
  9. import org.apache.shiro.authz.AuthorizationInfo;
  10. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  11. import org.apache.shiro.realm.AuthorizingRealm;
  12. import org.apache.shiro.subject.PrincipalCollection;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15.  
  16. import com.cdv.nsite.program.model.AppUser;
  17. import com.cdv.nsite.program.services.impl.AppUserServiceImpl;
  18.  
  19. public class MyRealm extends AuthorizingRealm {
  20.  
  21. private final static Logger logger = LoggerFactory.getLogger(MyRealm.class);
  22.  
  23. @Override
  24. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  25. logger.debug("登录验证后进行权限认证....");
  26. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  27. return info;
  28. }
  29.  
  30. @Override
  31. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  32. logger.debug("登录操作进行登录认证......");
  33. UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
  34.  
  35. AppUser user = SpringContextUtils.getBean(AppUserServiceImpl.class).getUserByName(token.getUsername());
  36. if (user == null) {
  37. // 没找到帐号
  38. throw new UnknownAccountException(
  39. "没有在本系统中找到对应的用户信息。");
  40. }
  41. //简单验证
  42. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
  43. user.getUsername(),user.getPassword(),getName());
  44.  
  45. return info;
  46. }
  47.  
  48. }

MyRealm.java

    Session相关:

  1. package com.ddd.program.config;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. import org.apache.shiro.session.Session;
  6. import org.apache.shiro.session.SessionListener;
  7. import org.springframework.stereotype.Component;
  8.  
  9. @Component
  10. public class MySessionListener implements SessionListener {
  11.  
  12. private final AtomicInteger sessionCount = new AtomicInteger(0);
  13.  
  14. @Override
  15. public void onStart(Session session) {
  16. sessionCount.incrementAndGet();
  17. System.out.println("登录+1=="+sessionCount.get());
  18. }
  19.  
  20. @Override
  21. public void onStop(Session session) {
  22. sessionCount.decrementAndGet();
  23. System.out.println("登录退出-1=="+sessionCount.get());
  24. }
  25.  
  26. @Override
  27. public void onExpiration(Session session) {
  28. sessionCount.decrementAndGet();
  29. System.out.println("登录过期-1=="+sessionCount.get());
  30.  
  31. }
  32.  
  33. public int getSessionCount() {
  34. return sessionCount.get();
  35. }
  36. }

MySessionListener.java

  3、添加静态页面:

    在resource文件夹下新建static或public文件夹,工程会默认找static文件夹下的index.*,没有在找public文件夹下的index.*;

  4、新建登录的接口和实现

   完整代码---> https://github.com/liangguang/springboot_18

结述:

  以上代码只是个例子,主要是获得登录的Session用作其他用途;

---------------------------------------------------添加热部署支持-----------------------

  1. <!-- 模板引擎 暂时不用 -->
  2. <!-- <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  5. </dependency> -->
  6. <!--
  7. devtools可以实现热部署。devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),注意:因为其采用的虚拟机机制,该项重启是很快的
  8. 如果设置SpringApplication.setRegisterShutdownHook(false),则自动重启将不起作用。
  9. 设置 spring.devtools.restart.enabled 属性为false,可以关闭该特性。
  10. -->
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-devtools</artifactId>
  14. <optional>true</optional>
  15. <!-- optional=true,依赖不会传递,-->
  16. </dependency>

添加devtools依赖

  1. spring.devtools.restart.enabled = true

application.properties中添加配置项;

Spring Boot 添加Shiro支持的更多相关文章

  1. Spring Boot 添加JSP支持【转】

    Spring Boot 添加JSP支持 大体步骤: (1)            创建Maven web project: (2)            在pom.xml文件添加依赖: (3)     ...

  2. (19)Spring Boot 添加JSP支持【从零开始学Spring Boot】

    [来也匆匆,去也匆匆,在此留下您的脚印吧,转发点赞评论: 您的认可是我最大的动力,感谢您的支持] 看完本文章您可能会有些疑问,可以查看之后的一篇博客: 81. Spring Boot集成JSP疑问[从 ...

  3. 19. Spring Boot 添加JSP支持【从零开始学Spring Boot】

    转:http://blog.csdn.net/linxingliang/article/details/52017140 这个部分比较复杂,所以单独创建一个工程来进行讲解: 大体步骤: (1)     ...

  4. Spring boot 加入shiro支持

    在项目添加依赖 <!-- shiro spring. --> <dependency> <groupId>org.apache.shiro</groupId& ...

  5. spring boot 添加jsp支持注意事项

    1.一定要使用war包<packaging>war</packaging>2.将provided改为compile,具体如下: <dependency> <g ...

  6. 快速搭建Spring Boot + Apache Shiro 环境

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 一.Apache Shiro 介绍及概念 概念:Apache Shiro是一个强大且易用的Java安全框 ...

  7. Spring Boot 集成Shiro和CAS

    Spring Boot 集成Shiro和CAS 标签: springshirocas 2016-01-17 23:03 35765人阅读 评论(22) 收藏 举报  分类: Spring(42)  版 ...

  8. Spring Boot 整合 Shiro ,两种方式全总结!

    在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...

  9. Springboot 系列(十七)迅速使用 Spring Boot Admin 监控你的 Spring Boot 程序,支持异常邮件通知

    1. Spring Boot Admin 是什么 Spring Boot Admin 是由 codecentric 组织开发的开源项目,使用 Spring Boot Admin 可以管理和监控你的 S ...

随机推荐

  1. jQuery静态方法isPlainObject,isEmptyObject方法使用和源码分析

    isPlainObject方法 测试对象是否是纯粹的对象(通过 "{}" 或者 "new Object" 创建的) 示例: //测试是否为纯粹的对象 jQuer ...

  2. 轻松掌握:JavaScript单例模式

    单例模式 定义:保证一个对象(类)仅有一个实例,并提供一个访问它的全局访问点: 实现原理:利用闭包来保持对一个局部变量的引用,这个变量保存着首次创建的唯一的实例; 主要用于:全局缓存.登录浮窗等只需要 ...

  3. 奇妙的CSS之布局与定位

    前言 关于布局与定位是Web前端开发里非常基础而又重要的部分.介绍相关知识的文章,很容易就可以找到.虽然,这方面的知识点不是很多,但我们如果不弄清楚,在运用时候往往会出现预料之外的布局,这些“意外”有 ...

  4. SharePoint 2013 激活标题字段外的Menu菜单

    前言 SharePoint 有个很特别的字段,就是标题(Title)字段,无论想要链接到项目,还是弹出操作项目的菜单,都是通过标题字段,一直以来需要的时候,都是通过将标题字段改名进行的. 其实,Sha ...

  5. iOS之 block,代替代理作为回调函数

    最近在弄一个视频会议的项目,但今天要说的跟视频基本没关系,我们来说一下在一个view中创建一个button,在controller中加载这个view 当button被点击后将时间响应传递给contro ...

  6. Python之基础

    # 需要导入字符编码,否则遇到中文会报错 # coding=utf-8 # 1 定义变量 a = 10 b = 2 c = a+b print(c) # 2 判断语句 score = 90 if sc ...

  7. tomcat 应用部署的几点注意

    将应用部署到Tomcat根目录的目的是可以通过"http://[ip]:[port]"直接访问应用,而不是使用"http://[ip]:[port]/[appName]& ...

  8. sp_executesql得到执行sql语句的返回值

    执行 sql语句,得到 变量的值 ' declare @Partition int; ); ); SET @SQLString = N'SELECT @RangeKeyOUT = $PARTITION ...

  9. linux中位置参数变量和预定义变量

    位置参数变量   预定义变量

  10. [转]Python 字符串操作实现代码(截取/替换/查找/分割)

    原文地址:http://www.jb51.net/article/38102.htm ps:好久没更新python代码了,这次用到了字符串,转来看看 Python 截取字符串使用 变量[头下标:尾下标 ...