Shrio安全框架使用方法
除非是下载源码,可以去Shiro官网下载,如果是在项目中使用,直接pom.xml文件中引入下方的依赖就可以使用,提取版本号(下方依赖统一使用这个版本,也方便后期更换版本),放到项目属性配置中
<properties>
<shiro.version>1.7.1</shiro.version>
</properties>
<!--------------------------------------假装有条分割线--------------------------------------->
<!-- shiro 依赖 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
在SSM框架集成了Shiro
在web.xml文件中,配置 shiro 拦截器
<!-- 加载spring配置文件、shiro配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:spring-shiro.xml
</param-value>
</context-param>
<!-- 配置 shiro 拦截器 -->
<filter>
<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>
spring-shiro.xml :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.xsd">
<description>Spring Shiro Configuration</description>
<!-- 配置 shiro 的核心组件:securityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 配置缓存 -->
<property name="cacheManager" ref="cacheManager"/>
<!-- 配置域realm,用户名,密码,角色都保存在域里:实现从数据库中获取用户信息,需要我们自己创建一个类(实现Realm接口) -->
<property name="realm" ref="shiroRealm"/>
</bean>
<!-- 配置ehcache缓存bean,导入ehcache并新建配置文件 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"></property>
</bean>
<!-- 配置自己realm实现 -->
<bean id="shiroRealm" class="com.erp.cloud.shiro.ShiroRealm"></bean>
<!-- 配置shiro的拦截规则,id必须和web.xml中的 shiro 拦截器名一致 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 身份认证失败,则跳转到登录页面的配置 -->
<property name="loginUrl" value="/login.jsp"/>
<!-- 登录成功后的页面 -->
<property name="successUrl" value="/index.jsp"/>
<!-- 权限认证失败,则跳转到指定页面 -->
<property name="unauthorizedUrl" value="/403.jsp"/>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
<!-- 注意:规则是有顺序的,从上到下,拦截范围必须是从小到大的 -->
<!-- url = 拦截规则(anon为匿名,authc为要登录后,才能访问,logout登出过滤) -->
/login/** = anon
/logout = logout
/**= authc
</value>
</property>
</bean>
</beans>
配置缓存 ,(这里使用的ehcache,可能现在用Redis的多,这个不常用,简单看一下)
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="java.io.tmpdir/Tmp_EhCache"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<defaultCache eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
springmvc.xml 中配置 Shiro 的注解
<!-- 配置shiro开启注解支持 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
自定义 ShiroRealm 域的实现
package com.list.cloud.shiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.HashSet;
import java.util.Set;
/**
* @ClassName: ShiroRealm
* @Description: 配置域
* @Author: 李斯特
* @Date
* ...
*/
public class ShiroRealm extends AuthorizingRealm {
/**
* 认证
*
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
String password = new String(token.getPassword());
System.out.println(username + "==========" + password);
// 根据用户名去数据库查询用户信息
// 做一些业务逻辑验证
// if(user.getStatus() == 0) {
// throw new UnknownAccountException("用户名已被禁用,请联系系统管理员!");
// }
/**
* principals: 可以使用户名,或登录用户的对象
* hashedCredentials: 从数据库中获取的密码
* credentialsSalt:密码加密的盐值
* RealmName: 类名(ShiroRealm)
*/
AuthenticationInfo info = new SimpleAuthenticationInfo(username, "123456", null, getName());
return info;
}
/**
* 授权
*
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = (String) SecurityUtils.getSubject().getPrincipal();
System.out.println("用户授权开始--------------------" + username + "---------------------");
if (username != null) {
Integer userId = 1;
// 根据用户ID获取用户权限和角色
Set<String> permissionSet = new HashSet<>();
permissionSet.add("addUser");
permissionSet.add("delUser");
permissionSet.add("updateUser");
permissionSet.add("getUser");
Set<String> roleSet = new HashSet<>();
permissionSet.add("Boss");
// 将我们的角色和权限交给shiro框架管理
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRoles(roleSet);
simpleAuthorizationInfo.addStringPermissions(permissionSet);
System.out.println("用户授权结束--------------------" + username + "---------------------");
return simpleAuthorizationInfo;
}
return null;
}
}
写一个登录的接口
@RequestMapping("/doLogin")
public String doLogin() {
// 1、认证的核心组件:获取 Subject 对象
Subject subject = SecurityUtils.getSubject();
// 2、将登陆表单封装成 token 对象
UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
try {
// 3、让 shiro 框架进行登录验证:
subject.login(token);
} catch (Exception e) {
e.printStackTrace();
return "login error";
}
return "redirect:/index.jsp";
}
shiro 标签
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!--
权限标签:https://blog.csdn.net/lizhiqiang1217/article/details/91129218
-->
<shiro:hasPermission name="addUser">添加用户</shiro:hasPermission>
<shiro:hasPermission name="addRole">添加角色</shiro:hasPermission>
以上就简单的用 shiro 控制了登录认证授权;
那其他的一些功能要求还得再去实现;
比如:系统必须登录后才可以访问等…
都看到这儿了,点个关注再走吧?
链接: 李斯特的博客.