1.Shiro基本介绍
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
三个核心组件:Subject,SecurityManager 和 Realms.
Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。但考虑到大多数目的和用途,你可以把它认为是Shiro的“用户”概念。
Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。
SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
Realm:Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。
Shiro内置了可以连接大量安全数据源(又名目录)的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果缺省的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。
2.Shiro的依赖
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.0</version>
</dependency>
3.自定义Realm
实际业务中,需要我们自定义realm实现用户认证和权限的管理。我们自定义的类需要继承AuthorizingRealm,重写两个主要的方法。具体案例代码如下:
public class ShiroRealm extends AuthorizingRealm {
private static final Logger LOGGER = LoggerFactory.getLogger(ShiroRealm.class);
@Autowired
private UsersService usersService;
@Autowired
private RoleMapper roleMapper;
/**
* 权限控制
*
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
LOGGER.info("======用户授权认证======");
String userName = principalCollection.getPrimaryPrincipal().toString();
//根据userName查询用户
Users users = new Users();
users.setAccount(userName);
users = usersService.getUser(users);
//根据用户roleId查询权限
Role role = roleMapper.selectByPrimaryKey(users.getRoleId());
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRole(role.getRoleName());
return simpleAuthorizationInfo;
}
/**
* 用户认证
*
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//获取登录用户名称
String userName = authenticationToken.getPrincipal().toString();
if (userName == null || StringUtils.isEmpty(userName)) {
return null;
}
Users users = new Users();
users.setAccount(userName);
Users user = usersService.getUser(users);
if (user != null) {
AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), getName());
return authenticationInfo;
}
return null;
}
}
4.spring-shiro.xml的配置
类似spring-mvc.xml的配置,用于spring加载Shiro必须的实体类,这里主要配置如下:
<?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">
<!-- 启用shrio授权注解拦截方式 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 装配 securityManager -->
<property name="securityManager" ref="securityManager"/>
<!-- 配置登陆页面 -->
<property name="loginUrl" value="/login"/>
<!-- 登陆成功后的一面 -->
<property name="successUrl" value="/index"/>
<property name="unauthorizedUrl" value="/index.jsp"/>
<!-- 具体配置需要拦截哪些 URL, 以及访问对应的 URL 时使用 Shiro 的什么 Filter 进行拦截. -->
<property name="filterChainDefinitions">
<value>
/index.jsp=anon
/login.jsp=anon
/login=anon
/doLogin=anon
/resources/**=anon
/index= roles[admin]
/logout = logout
/**=user
</value>
</property>
</bean>
<!-- 配置缓存管理器 -->
<!--<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">-->
<!--<!– 指定 ehcache 的配置文件 –>-->
<!--<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>-->
<!--</bean>-->
<!-- 配置进行授权和认证的 Realm -->
<bean id="myRealm" class="com.winning.shiro.ShiroRealm">
<!--<property name="userService" ref="userService"/>-->
</bean>
<!--<bean id="userService" class="com.gray.user.service.impl.UserServiceImpl"/>-->
<!-- 配置 Shiro 的 SecurityManager Bean. -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--<property name="cacheManager" ref="cacheManager"/>-->
<property name="realm" ref="myRealm"/>
</bean>
<!-- 配置 Bean 后置处理器: 会自动的调用和 Spring 整合后各个组件的生命周期方法. -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
5.web.xml的配置
在web.xml中增加Shiro过滤器。配置如下:
<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>
在web.xml中加载spring-shiro.xml。配置如下:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring.xml</param-value>
</context-param>
<!-- Spring监听器 -->
<listener>
<listenerclass>org.springframework.web.context.ContextLoaderListener</listenerclass>
</listener>
注意: spring-*.xml已经全都引入到spring.xml中,此处加载包括spring-mvc.xml(mvc控制),spring-shiro.xml(shiro),spring-mybatis.xml(数据源)和spring(包的扫描,注解的支持等)的配置。