Spring Mvc整合Apache Shiro
Apache Shiro简介
Apache Shiro
Apache Shiro是一个强大易用的java安全框架,虽然不如Spring Security强大,但是对于大部分项目而言也够用了。而且在SSM/SSH中整合Spring Security都是比较麻烦的操作,所以在以上两个框架中使用shiro更多一点。
常用技术栈
- SSM+Shiro
- Spring Boot/Spring Cloud + Spring Security
整合Shiro
目录结构
添加依赖(pom.xml)
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.0</version>
</dependency>
配置ShiroFilter(web.xml)
<filter>
<description>shiro 权限拦截</description>
<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>
新建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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- 1.配置 Shiro 的 SecurityManager Bean. -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="realm" ref="myRealm"/>
</bean>
<!-- 2.配置缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- 指定 ehcache 的配置文件 -->
<property name="cacheManagerConfigFile" value="classpath:spring/ehcache-shiro.xml"/>
</bean>
<!-- 3.配置进行授权和认证的 Realm -->
<bean id="myRealm" class="com.sqtg.shiro.ShiroRealm">
<!--<property name="userService" ref="userService"/>-->
</bean>
<!-- 4.配置 Bean生命周期后置处理器: 会自动的调用和 Spring 整合后各个组件的生命周期方法. -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 5.启用ioc容器中使用shiro的注解, 但必须在配置了LifecycleBeanPostProcessor之后才可以使用 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"></property>
</bean>
<!-- 6.配置ShiroFilter 6.1 id必须和 web.xml文件中配置的DelegatingFilterProxy的filter-name一致 6.2 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 装配 securityManager -->
<property name="securityManager" ref="securityManager"/>
<!-- 配置登陆页面 -->
<property name="loginUrl" value="/login.jsp"/>
<!-- 登陆成功后的页面 -->
<property name="successUrl" value="/user.jsp"/>
<!-- 没有权限的页面 -->
<property name="unauthorizedUrl" value="/index.jsp"/>
<!-- 配置哪些页面需要拦截,以及访问这些页面需要的权限 1.anon 可以匿名访问 2.authc 必须认证才可以访问 -->
<property name="filterChainDefinitions">
<value>
/swagger-ui.html=anon
/swagger-resources/** = anon
/v2/api-docs/** = anon
/webjars/springfox-swagger-ui/** = anon
/index.jsp=anon
/login.jsp=anon
/** = authc
</value>
</property>
</bean>
</beans>
新建shiro缓存配置文件(ehcache-shiro.xml)
<!--以下内容为直接复制的shiro samples里面的代码 https://github.com/apache/shiro/blob/master/samples/spring-mvc/src/main/resources/ehcache.xml-->
<!-- ~ 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. -->
<!-- EhCache XML configuration file used for Shiro spring sample application -->
<ehcache>
<!-- 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 -->
<diskStore path="java.io.tmpdir/shiro-spring-sample"/>
<!--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) -->
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
<!-- 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. -->
<cache name="shiro-activeSessionCache" maxElementsInMemory="10000" eternal="true" overflowToDisk="true" diskPersistent="true" diskExpiryThreadIntervalSeconds="600"/>
<cache name="org.apache.shiro.realm.SimpleAccountRealm.authorization" maxElementsInMemory="100" eternal="false" timeToLiveSeconds="600" overflowToDisk="false"/>
</ehcache>
实现自定义Realm
package com.sqtg.shiro;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** * 获取用户的角色和权限信息 * @author Administrator * */
public class ShiroRealm extends AuthorizingRealm {
private static Logger logger = LoggerFactory.getLogger(ShiroRealm.class);
@Autowired
private IClientService cs;
/** * 权限控制 * * @param principalCollection * @return */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
return simpleAuthorizationInfo;
}
/** * 用户认证 * * @param authenticationToken * @return * @throws AuthenticationException */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
}
以上就是配置shiro的全过程了,不出意外的话访问user.jsp将会自动跳转到login.jsp
可能会出现的问题
SSM整合Shiro出现no ContextLoaderListener registered的问题
还没有评论,来说两句吧...