在SSM框架中使用shiro。环境 使用idea工具。

最主要的大概是配置文件如何配置吧。

1配置maven依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.</modelVersion>
  6.  
  7. <groupId>com</groupId>
  8. <artifactId>shirodemo2</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11.  
  12. <name>shirodemo2 Maven Webapp</name>
  13. <!-- FIXME change it to the project's website -->
  14. <url>http://www.example.com</url>
  15.  
  16. <properties>
  17. <project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
  18. <maven.compiler.source>1.7</maven.compiler.source>
  19. <maven.compiler.target>1.7</maven.compiler.target>
  20. </properties>
  21.  
  22. <dependencies>
  23. <dependency>
  24. <groupId>junit</groupId>
  25. <artifactId>junit</artifactId>
  26. <version>4.12</version>
  27. <scope>test</scope>
  28. </dependency>
  29. <!--shiro需要用的依赖包-->
  30. <dependency>
  31. <groupId>org.apache.shiro</groupId>
  32. <artifactId>shiro-core</artifactId>
  33. <version>1.4.</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.apache.shiro</groupId>
  37. <artifactId>shiro-spring</artifactId>
  38. <version>1.4.</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.apache.shiro</groupId>
  42. <artifactId>shiro-web</artifactId>
  43. <version>1.4.</version>
  44. </dependency>
  45. <!--spring需要的依赖-->
  46. <dependency>
  47. <groupId>org.springframework</groupId>
  48. <artifactId>spring-context</artifactId>
  49. <version>5.1..RELEASE</version>
  50. </dependency>
  51. <dependency>
  52. <groupId>org.springframework</groupId>
  53. <artifactId>spring-webmvc</artifactId>
  54. <version>5.1..RELEASE</version>
  55. </dependency>
  56. <dependency>
  57. <groupId>org.springframework</groupId>
  58. <artifactId>spring-jdbc</artifactId>
  59. <version>5.1..RELEASE</version>
  60. </dependency>
  61. <dependency>
  62. <groupId>mysql</groupId>
  63. <artifactId>mysql-connector-java</artifactId>
  64. <version>5.1.</version>
  65. </dependency>
  66. <dependency>
  67. <groupId>org.mybatis</groupId>
  68. <artifactId>mybatis</artifactId>
  69. <version>3.5.</version>
  70. </dependency>
  71. <dependency>
  72. <groupId>org.mybatis</groupId>
  73. <artifactId>mybatis-spring</artifactId>
  74. <version>2.0.</version>
  75. </dependency>
  76. <!--json数据格式转换-->
  77. <dependency>
  78. <groupId>com.fasterxml.jackson.core</groupId>
  79. <artifactId>jackson-databind</artifactId>
  80. <version>2.9.</version>
  81. </dependency>
  82. <dependency>
  83. <groupId>com.alibaba</groupId>
  84. <artifactId>druid</artifactId>
  85. <version>1.1.</version>
  86. </dependency>
  87. <!--切面编程需要用到-->
  88. <dependency>
  89. <groupId>org.aspectj</groupId>
  90. <artifactId>aspectjweaver</artifactId>
  91. <version>1.9.</version>
  92. </dependency>
  93. </dependencies>
  94.  
  95. <build>
  96. <finalName>shirodemo2</finalName>
  97. <!--mybatis逆向工程-->
  98. <plugins>
  99. <plugin>
  100. <groupId>org.mybatis.generator</groupId>
  101. <artifactId>mybatis-generator-maven-plugin</artifactId>
  102. <version>1.3.</version>
  103. <configuration>
  104. <overwrite>true</overwrite>
  105. <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
  106. </configuration>
  107. <dependencies>
  108. <dependency>
  109. <groupId>mysql</groupId>
  110. <artifactId>mysql-connector-java</artifactId>
  111. <version>5.1.</version>
  112. </dependency>
  113. </dependencies>
  114.  
  115. </plugin>
  116. </plugins>
  117. <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
  118. <plugins>
  119. <plugin>
  120. <artifactId>maven-clean-plugin</artifactId>
  121. <version>3.1.</version>
  122. </plugin>
  123. <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
  124. <plugin>
  125. <artifactId>maven-resources-plugin</artifactId>
  126. <version>3.0.</version>
  127. </plugin>
  128. <plugin>
  129. <artifactId>maven-compiler-plugin</artifactId>
  130. <version>3.8.</version>
  131. </plugin>
  132. <plugin>
  133. <artifactId>maven-surefire-plugin</artifactId>
  134. <version>2.22.</version>
  135. </plugin>
  136. <plugin>
  137. <artifactId>maven-war-plugin</artifactId>
  138. <version>3.2.</version>
  139. </plugin>
  140. <plugin>
  141. <artifactId>maven-install-plugin</artifactId>
  142. <version>2.5.</version>
  143. </plugin>
  144. <plugin>
  145. <artifactId>maven-deploy-plugin</artifactId>
  146. <version>2.8.</version>
  147. </plugin>
  148. </plugins>
  149. </pluginManagement>
  150. </build>
  151. </project>

pom.xml

2.使用mybatis逆向工程 生成实体类

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  3. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  4. <generatorConfiguration>
  5. <!--逆向工程配置文件,通过在pom.xml的依赖于引用来根据数据库中的表生成实现类与dao接口以及映射文件-->
  6. <context id="mysql" targetRuntime="Mybatis3">
  7. <commentGenerator>
  8. <property name="suppressDate" value="true"/>
  9. <!-- 是否去除自动生成的注释 true:是 : false:否 -->
  10. <property name="suppressAllComments" value="true"/>
  11. </commentGenerator>
  12. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  13. connectionURL="jdbc:mysql://localhost:3306/bcs"
  14. userId="root" password="">
  15. </jdbcConnection>
  16. <!--存放生成实体类的路径,在idea中targetProject填写生成地址,eclipse中填写项目名-->
  17. <javaModelGenerator targetPackage="com.bpms.pojo" targetProject="src/main/java"/>
  18. <!--生成sql映射文件的路径,在idea中,文件会被标记,资源放到resources中,mapper.xml放到java中的话,需要在pom.xml进行额外配置-->
  19. <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
  20. <!--生成dao接口的目录,dao 数据访问对象,面向对象的数据访问接口-->
  21. <javaClientGenerator type="XMLMAPPER" targetPackage="com.bpms.dao" targetProject="src/main/java"/>
  22. <!--接口映射名可以自动生成 mapperName,也可以手动设置-->
  23. <!--tableName:数据库中的表名,mapperName:dao接口及mapper.xml映射文件名,domainObjectName:pojo实体类名-->
  24. <table tableName="t_auth" domainObjectName="Auth" enableDeleteByExample="false"
  25. enableUpdateByExample="false"
  26. enableSelectByExample="false"
  27. enableCountByExample="false"
  28. selectByExampleQueryId="false"/>
  29.  
  30. <table tableName="t_user" domainObjectName="User" enableDeleteByExample="false"
  31. enableUpdateByExample="false"
  32. enableSelectByExample="false"
  33. enableCountByExample="false"
  34. selectByExampleQueryId="false"/>
  35. <table tableName="t_role" domainObjectName="Role" enableDeleteByExample="false"
  36. enableUpdateByExample="false"
  37. enableSelectByExample="false"
  38. enableCountByExample="false"
  39. selectByExampleQueryId="false"/>
  40.  
  41. </context>
  42. <!--添加在pom.xml的build节点下的内容。-->
  43. <!--<plugins>
  44. <plugin>
  45. &lt;!&ndash;逆向工程的主要包&ndash;&gt;
  46. <groupId>org.mybatis.generator</groupId>
  47. <artifactId>mybatis-generator-maven-plugin</artifactId>
  48. <version>1.3.7</version>
  49. <configuration>
  50. <overwrite>true</overwrite>
  51. <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
  52. </configuration>
  53. &lt;!&ndash;要与数据库进行连接。依赖的驱动&ndash;&gt;
  54. <dependencies>
  55. <dependency>
  56. <groupId>mysql</groupId>
  57. <artifactId>mysql-connector-java</artifactId>
  58. <version>5.1.47</version>
  59. </dependency>
  60. </dependencies>
  61.  
  62. </plugin>
  63. </plugins>-->
  64. </generatorConfiguration>

generatorConfig.xml

3.创建applicationContext.xml  spring-mvc.xml spring-shiro.xml 。注意,创建的xml,以箭头指示的插件来创建。

  三个xml文件直接放在,resources目录下就好。后面再开始配置

4配置web.xml 配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  5. version="3.1">
  6. <!--web.xml 的加载顺序是:ServletContext -> context-param -> listener -> filter -> servlet ,而同个类型之间的实际程序调用的时候的顺序是根据对应的 mapping 的顺序进行调用的。-->
  7. <!--部署applicationContext的xml文件,如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml,自定义文件名可以在web.xml里加入contextConfigLocation这个context参数-->
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>classpath:applicationContext.xml,classpath:spring-shiro.xml</param-value>
  11. </context-param>
  12. <!--ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。-->
  13. <listener>
  14. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  15. </listener>
  16. <!--过滤器配置的顺序,过滤器最好配置的位置是在org.springframework.web.filter.CharacterEncodingFilter 之后,就是处理好字符集就是Shiro的过滤器。这里没有进行处理-->
  17. <filter>
  18. <filter-name>shiroFilter</filter-name><!--这个shiroFilter不能随便,在spring-shiro.xml中ShiroFilterFactoryBean的id要一致-->
  19. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  20. </filter>
  21. <filter-mapping>
  22. <filter-name>shiroFilter</filter-name>
  23. <url-pattern>/*</url-pattern>
  24. </filter-mapping>
  25. <!--使用Spring MVC,配置DispatcherServlet是第一步。DispatcherServlet是一个Servlet,,所以可以配置多个DispatcherServlet-->
  26. <!--DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据某某规则分发到目标Controller(我们写的Action)来处理。-->
  27. <!--在DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为[servlet-name]-servlet.xml 的配置文件,生成文件中定义的bean。-->
  28. <servlet>
  29. <servlet-name>springmvc</servlet-name>
  30. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  31. <!--指明了配置文件的文件名,不使用默认配置文件名,而使用dispatcher-servlet.xml配置文件。-->
  32. <init-param>
  33. <param-name>contextConfigLocation</param-name>
  34. <param-value>classpath:spring-mvc.xml</param-value>
  35. </init-param>
  36. <!--是启动顺序,让这个Servlet随Servlet容器一起启动。-->
  37. <load-on-startup>1</load-on-startup>
  38. </servlet>
  39. <servlet-mapping>
  40. <servlet-name>springmvc</servlet-name>
  41. <url-pattern>/</url-pattern>
  42. </servlet-mapping>
  43. </web-app>
  44. <!--在web.xml中要注入的配置文件 有三个 applicationContext(1) spring-mvc(2) spring-shiro(3),但是 1 2 3 却不在一起
  45. 1 3 在 context 标签中 最先加入的 。2在servlet标签中 设置了加载优先级。还是没有 context中的优先。
  46. 一般 2 更倾向于 与网络 Tomcat 交互 。1 3更倾向于 与数据库 本地 进行交互。
  47. 请求先到达过滤器再到拦截器
  48. -->

web.xml

5.配置applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--表示启动spring的组件扫描功能(从spring2.5版本开始)。即扫描base-package包或者子包下面的Java文件,如果扫描到有@controller、@Service、@Repository、@Component等注解的java类,就会将这些bean注册到工厂中。
  7. 还可以使用分号来分隔多个扫描包。如果在配置文件中配置了<context:component-scan />,就不用在配置<context:annotation-config/>,因为前者已经包含了后者。<context:annotation-config/>的作用是向spring容器注入
  8. AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 及RequiredAnnotationBeanPostProcessor 四个beanPostProcessor。从而使得@Autowired等注解生效。-->
  9. <context:component-scan base-package="com.*"/>
  10.  
  11. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
  12. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  13. <property name="username" value="root"/>
  14. <property name="password" value=""/>
  15. <property name="url" value="jdbc:mysql://localhost:3306/bcs"/>
  16. </bean>
  17.  
  18. <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
  19. <property name="dataSource" ref="dataSource"/>
  20. <!--sql文件映射路径-->
  21. <property name="mapperLocations" value="classpath:mapper/*.xml"/>
  22. </bean>
  23. <!-- 自动扫描注册mapper接口类(接口类实现mybatis),根据 sessionFactory对应的mapperLocations生成接口类的实现-->
  24. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  25. <property name="basePackage" value="com.bpms.dao"/>
  26. <property name="sqlSessionFactoryBeanName" value="sessionFactory"/><!--这个是value值不是ref映射-->
  27. </bean>
  28. <!--以上是主要是把mybatis中的配置使用applicationContext来进行。连接数据库相关的信息。包括 -->
  29. </beans>
  30. <!--个人认为,在applicationContext中进行的配置的。更偏向与后台代码逻辑与数据库之间,spring-mvc.xml中的配置更偏向与 后台代码逻辑与前台展示之间-->

applicationContext.xml

6.配置spring-mvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  7. <!-- 使用组件扫描的方式可以一次扫描多个Controller,自动扫描方式,扫描包下面所有的Controller,可以使用注解来指定访问路径 -->
  8. <context:component-scan base-package="com.bpms"/>
  9. <!-- 配置注解的处理器映射器和处理器适配器 -->
  10. <mvc:annotation-driven/>
  11. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  12. <property name="prefix" value="/"/>
  13. <property name="suffix" value=".jsp"/>
  14. </bean>
  15.  
  16. <!--配置spring shiro 支持aop注解-->
  17. <!--true针对类进行代理-->
  18. <aop:config proxy-target-class="true"/>
  19. <!--配置使aop注解生效的通知,securityManager的详细配置在spring-shiro.xml中进行-->
  20. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  21. <property name="securityManager" ref="securityManager"/>
  22. </bean>
  23.  
  24. <!--静态资源的请求-->
  25. <mvc:resources mapping="/**" location="/"/>
  26. </beans>

spring-mvc.xml

7.配置spring-shiro.xml   编写 realm

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5.  
  6. <!--配置shiro过滤器;id必须与web.xml中一致,对远程来访问的的 url 按照一定的格式进行匹配-->
  7. <bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiroFilter">
  8. <!-- 没有登录重定向到登录页面 -->
  9. <property name="loginUrl" value="/login.html"/>
  10. <!-- 没有权限跳转的页面 -->
  11. <property name="unauthorizedUrl" value="/403.html"/>
  12. <!-- shiro拦截器 -->
  13. <!--anon(都是shiro提供的filter):匿名访问(没有登录的情况下也可以访问),一般用来忽略静态资源
  14.         authc:必须要认证以后才能访问的
  15.         logout:注销要用到的-->
  16. <property name="filterChainDefinitions">
  17. <value>
  18. /login.html=anon
  19. /css/*=anon
  20. /static/*=anon
  21. /js/*=anon
  22. /doLogin=anon
  23. /*=authc
  24. </value>
  25. </property>
  26. <!-- 调用我们配置的权限管理器 -->
  27. <property name="securityManager" ref="securityManager"/>
  28. </bean>
  29.  
  30. <!--配置安全管理器,注入域,缓存,remember会话都在这里注入,需要注入到 在spring-mcv中配置的对象中-->
  31. <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
  32. <property name="realm" ref="customRealm"/>
  33. <property name="cacheManager" ref="cacheManager"/>
  34. </bean>
  35.  
  36. <!--自定义域,可以在bean外面配置再添加进来,也可以在直接在bean里面配置-->
  37. <bean class="com.bpms.shiro.CustomRealm" id="customRealm">
  38. <property name="credentialsMatcher" ref="matcher"/>
  39. </bean>
  40.  
  41. <!--加密算法与次数-->
  42. <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher" id="matcher">
  43. <property name="hashAlgorithmName" value="md5"/>
  44. <!--之前的加密次数没有设置,这里注释掉-->
  45. <!--<property name="hashIterations" value="2"/>-->
  46. </bean>
  47.  
  48. <!--缓存-->
  49. <bean class="org.apache.shiro.cache.MemoryConstrainedCacheManager" id="cacheManager"/>
  50. </beans>
  51. <!-- 启动shiro注解(必须放在spring MVC 配置文件那边) -->
  52. <!-- <aop:config proxy-target-class="true"></aop:config>
  53. 可以配置在shiro或springmvc这里
  54. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor" >
  55. <property name="securityManager"  ref="securityManager"></property>
  56. </bean> -->

spring-shiro.xml

自定义的realm

  1. package com.bpms.shiro;
  2.  
  3. import com.bpms.pojo.User;
  4. import com.bpms.service.AuthService;
  5. import com.bpms.service.UserService;
  6. import org.apache.shiro.authc.*;
  7. import org.apache.shiro.authz.AuthorizationInfo;
  8. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  9. import org.apache.shiro.realm.AuthorizingRealm;
  10. import org.apache.shiro.subject.PrincipalCollection;
  11. import org.apache.shiro.util.ByteSource;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13.  
  14. import java.util.HashSet;
  15. import java.util.List;
  16. import java.util.Set;
  17.  
  18. public class CustomRealm extends AuthorizingRealm {
  19.  
  20. @Autowired
  21. private UserService userService;
  22.  
  23. @Autowired
  24. private AuthService authService;
  25.  
  26. @Override
  27. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  28. User user = (User) principalCollection.getPrimaryPrincipal();
  29. //认证通过的话,是否到达授权
  30. List<String> perms = authService.findPermsByUserName(user.getUserName());//连接服务层从数据库中查找权限添加进来
  31. System.out.println("当前用户拥有的权限许可:");
  32. for (String str : perms) {
  33. System.out.println(str + "------授权");
  34. }
  35.  
  36. Set set = new HashSet(perms);
  37. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  38. info.setStringPermissions(set);
  39. return info;
  40. }
  41.  
  42. @Override
  43. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  44. String userName = (String) authenticationToken.getPrincipal();
  45. System.out.println("认证userName:" + userName);//前台的数据是否传到身份认证这里
  46. User user = userService.findUserByName(userName);
  47. System.out.println("数据库用户:" + user);
  48. if (user == null) {
  49. throw new UnknownAccountException("当前用户不存");
  50. }
  51. //把根据用户名查找到的密码作为参数,与根据登录时传的数据生成的token进行匹配
  52. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
  53. //如果加密了,必须指定盐值
  54. info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
  55. return info;
  56. }
  57. }

CustomRealm.java

8.前台用于验证的一些html

  8.1.认证过的用户,访问未授权的路径,跳转的结果。何时出发 看 controller 中的代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. 没有权限
  9. </body>
  10. </html>

403.xml

  8.2.登录界面,未进行认证需求。即不认证也可以进行访问,不然登不进来。(访问登录界面,登录界面方法的认证路径,退出,等都不需要设置认证)

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <form action="doLogin" method="post">
  9. 用户名:<input type="text" name="userName"> <br>
  10. 密码: <input type="password" name="password"> <br>
  11. <input type="submit" value="登录">
  12. </form>
  13. </body>
  14. </html>

login.html

  8.3,shiro前端对用户权限的一些操作,不难,需要记一下。也是登录,认证成功时跳转的页面

  1. <%@ page language="java" pageEncoding="UTF-8" %>
  2. <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
  3. <html>
  4. <body>
  5. <h2>Hello World!</h2>
  6. <%--获取当前登录用户的用户名,登陆成功,信息通过token保存在 shirosession域中--%>
  7. welcome <shiro:principal property="userName"> </shiro:principal>!!!!
  8. <br>
  9. 需要认证的连接 <br>
  10. <shiro:hasPermission name="sys:user:list">
  11. <a href="list">查看</a>
  12. </shiro:hasPermission>
  13.  
  14. <shiro:hasPermission name="sys:role:delete">
  15. <a href="delete">删除</a>
  16. </shiro:hasPermission>
  17. <shiro:hasPermission name="sys:user:update">
  18. <a href="update">修改</a>
  19. </shiro:hasPermission>
  20. <shiro:hasPermission name="sys:user:save">
  21. <a href="insert">添加</a>
  22. </shiro:hasPermission>
  23. <br>
  24. 不需要认证的连接<br>
  25. <a href="delete">delete</a>
  26.  
  27. <a href="logout">退出系统</a>
  28.  
  29. <p>
  30. 数据库中admin用户是系统管理员 <br>
  31. 拥有的权限id 1,2,12,13,14,15,16,31,32<br>
  32. 权限id 中,有许可的都是下面这些<br>
  33. sys:role:list
  34. sys:role:save
  35. sys:role:update
  36. sys:role:delete<<br>
  37. 对应的上述的 shiro 标签,如果admin用户拥有的许可中有能与 shiro 标签中要求的的许可匹配,就会显示。shiro标签包含的内容<br>
  38. 这个用于在前台隐藏访问路径。如果有人知道,之前通过http进行请求,需要在后台进行认证
  39. </p>
  40. <p>
  41. @RequiresPermissions({"sys:user:delete"})<br>
  42. 如果前台的访问的路径需要认证被shiro拦截之后。当前用户已经通过认证。<br>
  43. 如果访问的路径被前端控制器,转发到相应的handler 中。对应的方法有这个注解。<br>
  44. 说明。需要这个认证过的用户,要有这个权限 "sys:user:delete",才可以进入 handler中。<br>
  45. "sys:user:delete"这样写只是一种规范,只要在realm中给该用户授权的 字段 和对应handler要求的字段一致,就可以进入handler。
  46.  
  47. </p>
  48.  
  49. </body>
  50. </html>

index.html

9.后台对认证过的用户,权限限制的配置。通过不同的注解,对权限或者角色(还可以附加 与 或的关系)

@RequiresAuthentication 表示当前Subject已经通过login进行了身份验证;即Subject. isAuthenticated()返回true。

@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)

表示当前Subject需要角色admin和user。

@RequiresPermissions (value={“user:update”, “user:delete”}, logical= Logical.OR)

表示当前Subject需要权限user:update或user:delete

  1. package com.bpms.controller;
  2.  
  3. import com.bpms.pojo.User;
  4. import org.apache.shiro.SecurityUtils;
  5. import org.apache.shiro.authc.AuthenticationException;
  6. import org.apache.shiro.authc.UsernamePasswordToken;
  7. import org.apache.shiro.authz.UnauthorizedException;
  8. import org.apache.shiro.authz.annotation.RequiresPermissions;
  9. import org.apache.shiro.crypto.hash.Md5Hash;
  10. import org.apache.shiro.subject.Subject;
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.web.bind.annotation.ExceptionHandler;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.ResponseBody;
  15. import org.springframework.web.servlet.ModelAndView;
  16.  
  17. @Controller
  18. public class UserController {
  19.  
  20. @RequestMapping("/doLogin")
  21. public String doLogin(User user) {
  22. System.out.println("doLogin:" + user);//用于检测请求是否走到了这一步,并查看请求的信息
  23. Subject subject = SecurityUtils.getSubject();
  24. UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
  25. try {
  26. Md5Hash md5Hash = new Md5Hash(user.getPassword(), "admin");
  27. System.out.println(md5Hash.toString());//因为密码不对,按照自己定义的加密方式,获得加密的密码,更新到数据库中。
  28. subject.login(token);
  29. return "redirect:/index.jsp";
  30. } catch (AuthenticationException e) {
  31. e.printStackTrace();
  32. return "redirect:/login.html";
  33. }
  34.  
  35. }
  36.  
  37. @RequestMapping("/logout")
  38. public String logout() {
  39. Subject subject = SecurityUtils.getSubject();
  40. subject.logout();
  41. return "redirect:/login.html";
  42. }
  43.  
  44. @RequestMapping("/insert")
  45. @ResponseBody
  46. public String insert() {
  47. return "insert";
  48. }
  49.  
  50. @RequestMapping("/delete")
  51. @ResponseBody
  52. @RequiresPermissions({"sys:user:delete"})//需要被认证的用户拥有的 权限 中有可以匹配 该字段的。请求才可以进入方法中
  53. public String delete() { //防止前台没有显示访问路径的时候,通过url恶意访问
  54. return "delete";
  55. }
  56.  
  57. @RequestMapping("/list")
  58. @ResponseBody
  59. public String list() {
  60. return "list";
  61. }
  62.  
  63. @RequestMapping("/update")
  64. @ResponseBody
  65. public String update() {
  66. return "update";
  67. }
  68.  
  69. @ExceptionHandler(UnauthorizedException.class)//认证的过用户,访问了没有权限的handler,进不去时,跳转的页面(一般页面进行了限制,触发这个很可能时恶意访问)
  70. public ModelAndView unauthorizedException() {
  71. ModelAndView modelAndView = new ModelAndView();
  72. modelAndView.setViewName("redirect:/403.html");
  73. return modelAndView;
  74. }
  75.  
  76. }

UserController

shiro三连斩之第二斩(SSM)的更多相关文章

  1. shiro三连斩之第一斩

    通过JavaSE,创建不同的 realm ,由简单到复杂一步步的深入的理解shiro完成认证与授权内在联系 推荐从下向上一步步的测试,每一个方法都有详细的注释,说明  从哪里来-->到哪里去,理 ...

  2. shiro三连斩之第三斩,整合 springboot

    shiro爱springboot中使用 ,还有thymeleaf前端框架.主要是如何配置 pom.xml配置依赖 <?xml version="1.0" encoding=& ...

  3. shiro三连斩之概念

    1, 什么是Shiro? Shiro是一个安全框架,用于解决系统的认证和授权问题,同时提供了会话管理,数据加密,与WEB集成,缓存等机制. Authentication:身份认证/登录,验证用户是不是 ...

  4. 《CLR.via.C#第三版》第二部分第4,5章节读书笔记(二)

    这两章全是理论性的东西,我觉得不必过于钻牛角尖.理论这东西,只有在长期的实践中去慢慢领悟才会深刻.下面我只写些我认为重要的关键知识. (一)类型转换 知识点:向基类型的转换被认为是一种安全的隐式转换: ...

  5. 《CLR.via.C#第三版》第二部分第8,9章节读书笔记(四)

    三种类型的构造方法: 实例构造器(引用类型):实例构造器永远不能被继承(所以方法前没有修饰符):如果类的修饰符为static(sealed和abstract),编译器根本不会在类的定义中生成一个默认构 ...

  6. 《CLR.via.C#第三版》第二部分第6,7章节读书笔记(三)

    第6章讲的是类型和成员基础 重要认知:虚方法 虚方法的设计原则:设计一个类型时,应尽量减少所定义的虚方法的数量. 首先,调用虚方法的速度比调用非虚方法慢. 其次,JIT编译器不能内嵌虚方法,这进一步影 ...

  7. Apache Shiro(三)-登录认证和权限管理MD5加密

    md5 加密 在前面的例子里,用户密码是明文的,这样是有巨大风险的,一旦泄露,就不好了.所以,通常都会采用非对称加密,什么是非对称呢?就是不可逆的,而 md5 就是这样一个算法.如代码所示 123 用 ...

  8. Shiro -- (三) 自定义Realm

    简介: Realm:域,Shiro 从从 Realm 获取安全数据(如用户.角色.权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定 ...

  9. SpringBoot整合Shiro 三:整合Mybatis

    搭建环境见: SpringBoot整合Shiro 一:搭建环境 shiro配置类见: SpringBoot整合Shiro 二:Shiro配置类 整合Mybatis 添加Maven依赖 mysql.dr ...

随机推荐

  1. LeetCode174-Dungeon Game-数组,动态规划

    题目描述 The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dun ...

  2. springboot整合ActiveMQ,配置问题

    1.ActiveMQ的安装和相关配置修改 去官网下载安装包解压至文件夹 双击打开 打开浏览器输入 http://127.0.0.1:8161 到此activeMQ就安装好了 2.springboot工 ...

  3. java扫描文件。

    前言:一步一步来实现迷你ioc框架,前面的容器工厂也是一个铺垫,这次的扫描文件也是一个铺垫…… 需求:扫描当前项目下所有文件.包括文件夹下文件夹里面的文件.利用递归进行扫描 ScanFileUtil类 ...

  4. idea Debug快捷键

    快捷键 介绍 F7 在 Debug 模式下,进入下一步,如果当前行断点是一个方法,则进入当前方法体内, 如果该方法体还有方法,则不会进入该内嵌的方法中 * F8 在 Debug 模式下,进入下一步,如 ...

  5. System.InvalidOperationException:“线程间操作无效: 从不是创建控件“btnSearch”的线程访问它。

    System.InvalidOperationException:“线程间操作无效: 从不是创建控件“btnSearch”的线程访问它.”这个问题属于跨线程问题 在Form1重载中写上一行代码 Sys ...

  6. 牛客 黑龙江大学程序设计竞赛重现 19-4-25 D

    题意: n项工作 1~n  工时s[i] ~e[i], 工时有覆盖的工作不能被同一台机器同时操作, 问完成所有工作的最少机器数 思路:前缀差分和 e.g. a            2 3 4    ...

  7. magic_quotes_gpc的作用

    magic_quotes_gpc设置是否自动为GPC(get,post,cookie)传来的数据中的\'\"\\加上反斜 线.可以用get_magic_quotes_gpc()检测系统设置. ...

  8. Cocos Creator学习五:触摸和重力传感响应事件

    1.移动设备上主要涉及触摸响应事件以及重力传感响应事件的处理. 事件主要分两类: 针对节点事件处理的节点响应事件cc.Node.EventType(主要是触摸响应事件和鼠标响应事件): 针对全局系统事 ...

  9. Project Euler 75: Singular integer right triangles

    题目链接 思路: 勾股数组,又称毕达格拉斯三元组. 公式:a = s*t b = (s^2 - t^2) / 2 c = (s^2 + t^2) / 2 s > t >=1 且为互质的奇数 ...

  10. 【sock_stream和sock_dgram】、 【AF_INET和AF_UNIX】

    [sock_stream和sock_dgram] 1.sock_stream 是有保障的(即能保证数据正确传送到对方)面向连接的SOCKET,多用于资料(如文件)传送. 2.sock_dgram 是无 ...