Spring Mvc整合Apache Shiro

ゞ 浴缸里的玫瑰 2022-12-28 09:27 242阅读 0赞

Apache Shiro简介

Apache Shiro

Apache Shiro是一个强大易用的java安全框架,虽然不如Spring Security强大,但是对于大部分项目而言也够用了。而且在SSM/SSH中整合Spring Security都是比较麻烦的操作,所以在以上两个框架中使用shiro更多一点。

常用技术栈

  • SSM+Shiro
  • Spring Boot/Spring Cloud + Spring Security

整合Shiro

目录结构

e316ae39db00a76b9c8d83d2d9e6d5d9.png

添加依赖(pom.xml)

  1. <dependency>
  2. <groupId>org.apache.shiro</groupId>
  3. <artifactId>shiro-core</artifactId>
  4. <version>1.7.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.shiro</groupId>
  8. <artifactId>shiro-web</artifactId>
  9. <version>1.7.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.shiro</groupId>
  13. <artifactId>shiro-ehcache</artifactId>
  14. <version>1.7.0</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.shiro</groupId>
  18. <artifactId>shiro-spring</artifactId>
  19. <version>1.7.0</version>
  20. </dependency>

配置ShiroFilter(web.xml)

  1. <filter>
  2. <description>shiro 权限拦截</description>
  3. <filter-name>shiroFilter</filter-name>
  4. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  5. <init-param>
  6. <param-name>targetFilterLifecycle</param-name>
  7. <param-value>true</param-value>
  8. </init-param>
  9. </filter>
  10. <filter-mapping>
  11. <filter-name>shiroFilter</filter-name>
  12. <url-pattern>/*</url-pattern>
  13. </filter-mapping>

新建shiro配置文件(spring-shiro.xml)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
  3. <!-- 1.配置 Shiro 的 SecurityManager Bean. -->
  4. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  5. <property name="cacheManager" ref="cacheManager"/>
  6. <property name="realm" ref="myRealm"/>
  7. </bean>
  8. <!-- 2.配置缓存管理器 -->
  9. <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
  10. <!-- 指定 ehcache 的配置文件 -->
  11. <property name="cacheManagerConfigFile" value="classpath:spring/ehcache-shiro.xml"/>
  12. </bean>
  13. <!-- 3.配置进行授权和认证的 Realm -->
  14. <bean id="myRealm" class="com.sqtg.shiro.ShiroRealm">
  15. <!--<property name="userService" ref="userService"/>-->
  16. </bean>
  17. <!-- 4.配置 Bean生命周期后置处理器: 会自动的调用和 Spring 整合后各个组件的生命周期方法. -->
  18. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
  19. <!-- 5.启用ioc容器中使用shiro的注解, 但必须在配置了LifecycleBeanPostProcessor之后才可以使用 -->
  20. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
  21. </bean>
  22. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  23. <property name="securityManager" ref="securityManager"></property>
  24. </bean>
  25. <!-- 6.配置ShiroFilter 6.1 id必须和 web.xml文件中配置的DelegatingFilterProxy的filter-name一致 6.2 -->
  26. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  27. <!-- 装配 securityManager -->
  28. <property name="securityManager" ref="securityManager"/>
  29. <!-- 配置登陆页面 -->
  30. <property name="loginUrl" value="/login.jsp"/>
  31. <!-- 登陆成功后的页面 -->
  32. <property name="successUrl" value="/user.jsp"/>
  33. <!-- 没有权限的页面 -->
  34. <property name="unauthorizedUrl" value="/index.jsp"/>
  35. <!-- 配置哪些页面需要拦截,以及访问这些页面需要的权限 1.anon 可以匿名访问 2.authc 必须认证才可以访问 -->
  36. <property name="filterChainDefinitions">
  37. <value>
  38. /swagger-ui.html=anon
  39. /swagger-resources/** = anon
  40. /v2/api-docs/** = anon
  41. /webjars/springfox-swagger-ui/** = anon
  42. /index.jsp=anon
  43. /login.jsp=anon
  44. /** = authc
  45. </value>
  46. </property>
  47. </bean>
  48. </beans>

新建shiro缓存配置文件(ehcache-shiro.xml)

  1. <!--以下内容为直接复制的shiro samples里面的代码 https://github.com/apache/shiro/blob/master/samples/spring-mvc/src/main/resources/ehcache.xml-->
  2. <!-- ~ Licensed to the Apache Software Foundation (ASF) under one ~ or more contributor license agreements. See the NOTICE file ~ distributed with this work for additional information ~ regarding copyright ownership. The ASF licenses this file ~ to you under the Apache License, Version 2.0 (the ~ "License"); you may not use this file except in compliance ~ with the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, ~ software distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the License for the ~ specific language governing permissions and limitations ~ under the License. -->
  3. <!-- EhCache XML configuration file used for Shiro spring sample application -->
  4. <ehcache>
  5. <!-- Sets the path to the directory where cache .data files are created. If the path is a Java System Property it is replaced by its value in the running VM. The following properties are translated: user.home - User's home directory user.dir - User's current working directory java.io.tmpdir - Default temp file path -->
  6. <diskStore path="java.io.tmpdir/shiro-spring-sample"/>
  7. <!--Default Cache configuration. These will applied to caches programmatically created through the CacheManager. The following attributes are required: maxElementsInMemory - Sets the maximum number of objects that will be created in memory eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element is never expired. overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit. The following attributes are optional: timeToIdleSeconds - Sets the time to idle for an element before it expires. i.e. The maximum amount of time between accesses before an element expires Is only used if the element is not eternal. Optional attribute. A value of 0 means that an Element can idle for infinity. The default value is 0. timeToLiveSeconds - Sets the time to live for an element before it expires. i.e. The maximum time between creation time and when an element expires. Is only used if the element is not eternal. Optional attribute. A value of 0 means that and Element can live for infinity. The default value is 0. diskPersistent - Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value is 120 seconds. memoryStoreEvictionPolicy - Policy would be enforced upon reaching the maxElementsInMemory limit. Default policy is Least Recently Used (specified as LRU). Other policies available - First In First Out (specified as FIFO) and Less Frequently Used (specified as LFU) -->
  8. <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
  9. <!-- We want eternal="true" (with no timeToIdle or timeToLive settings) because Shiro manages session expirations explicitly. If we set it to false and then set corresponding timeToIdle and timeToLive properties, ehcache would evict sessions without Shiro's knowledge, which would cause many problems (e.g. "My Shiro session timeout is 30 minutes - why isn't a session available after 2 minutes?" Answer - ehcache expired it due to the timeToIdle property set to 120 seconds.) diskPersistent=true since we want an enterprise session management feature - ability to use sessions after even after a JVM restart. -->
  10. <cache name="shiro-activeSessionCache" maxElementsInMemory="10000" eternal="true" overflowToDisk="true" diskPersistent="true" diskExpiryThreadIntervalSeconds="600"/>
  11. <cache name="org.apache.shiro.realm.SimpleAccountRealm.authorization" maxElementsInMemory="100" eternal="false" timeToLiveSeconds="600" overflowToDisk="false"/>
  12. </ehcache>

实现自定义Realm

  1. package com.sqtg.shiro;
  2. import org.apache.shiro.realm.AuthorizingRealm;
  3. import org.apache.shiro.authz.AuthorizationInfo;
  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.authz.SimpleAuthorizationInfo;
  8. import org.apache.shiro.subject.PrincipalCollection;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. /** * 获取用户的角色和权限信息 * @author Administrator * */
  12. public class ShiroRealm extends AuthorizingRealm {
  13. private static Logger logger = LoggerFactory.getLogger(ShiroRealm.class);
  14. @Autowired
  15. private IClientService cs;
  16. /** * 权限控制 * * @param principalCollection * @return */
  17. @Override
  18. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  19. SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
  20. return simpleAuthorizationInfo;
  21. }
  22. /** * 用户认证 * * @param authenticationToken * @return * @throws AuthenticationException */
  23. @Override
  24. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  25. return null;
  26. }
  27. }

以上就是配置shiro的全过程了,不出意外的话访问user.jsp将会自动跳转到login.jsp

可能会出现的问题

SSM整合Shiro出现no ContextLoaderListener registered的问题

发表评论

表情:
评论列表 (有 0 条评论,242人围观)

还没有评论,来说两句吧...

相关阅读