本文小编将基于 SpringBoot集成 Shiro实现动态uri权限,由前端vue在页面配置uri,Java后端动态刷新权限,不用重启项目,以及在页面分配给用户 角色、 按钮、uri权限后,后端动态分配权限,用户无需在页面重新登录才能获取最新权限,一切权限动态加载,灵活配置
成都创新互联专注于本溪网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供本溪营销型网站建设,本溪网站制作、本溪网页设计、本溪网站官网定制、小程序开发服务,打造本溪网络公司原创品牌,更为您提供本溪网站排名全网营销落地服务。
温馨小提示:案例demo源码附文章末尾,有需要的小伙伴们可参考哦 ~
1.4.0
3.1.0
org.springframework.boot
spring-boot-starter-aop
org.springframework.boot
spring-boot-starter-data-redis-reactive
org.apache.shiro
shiro-spring
${shiro-spring.version}
org.crazycake
shiro-redis
${shiro-redis.version}
doGetAuthenticationInfo
:身份认证 (主要是在登录时的逻辑处理)doGetAuthorizationInfo
:登陆认证成功后的处理 ex: 赋予角色和权限【 注:用户进行权限验证时 Shiro会去缓存中找,如果查不到数据,会执行doGetAuthorizationInfo这个方法去查权限,并放入缓存中 】
-> 因此我们在前端页面分配用户权限时 执行清除shiro缓存的方法即可实现动态分配用户权限 @Slf4j
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Autowired
private MenuMapper menuMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public String getName() {
return "shiroRealm";
}
/**
* 赋予角色和权限:用户进行权限验证时 Shiro会去缓存中找,如果查不到数据,会执行这个方法去查权限,并放入缓存中
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
// 获取用户
User user = (User) principalCollection.getPrimaryPrincipal();
Integer userId =user.getId();
// 这里可以进行授权和处理
Set rolesSet = new HashSet<>();
Set permsSet = new HashSet<>();
// 获取当前用户对应的权限(这里根据业务自行查询)
List roleList = roleMapper.selectRoleByUserId( userId );
for (Role role:roleList) {
rolesSet.add( role.getCode() );
List
@Configuration
public class ShiroConfig {
private final String CACHE_KEY = "shiro:cache:";
private final String SESSION_KEY = "shiro:session:";
/**
* 默认过期时间30分钟,即在30分钟内不进行操作则清空缓存信息,页面即会提醒重新登录
*/
private final int EXPIRE = 1800;
/**
* Redis配置
*/
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
// @Value("${spring.redis.password}")
// private String password;
/**
* 开启Shiro-aop注解支持:使用代理方式所以需要开启代码支持
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
/**
* Shiro基础配置
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager, ShiroServiceImpl shiroConfig){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 自定义过滤器
Map filtersMap = new LinkedHashMap<>();
// 定义过滤器名称 【注:map里面key值对于的value要为authc才能使用自定义的过滤器】
filtersMap.put( "zqPerms", new MyPermissionsAuthorizationFilter() );
filtersMap.put( "zqRoles", new MyRolesAuthorizationFilter() );
filtersMap.put( "token", new TokenCheckFilter() );
shiroFilterFactoryBean.setFilters(filtersMap);
// 登录的路径: 如果你没有登录则会跳到这个页面中 - 如果没有设置值则会默认跳转到工程根目录下的"/login.jsp"页面 或 "/login" 映射
shiroFilterFactoryBean.setLoginUrl("/api/auth/unLogin");
// 登录成功后跳转的主页面 (这里没用,前端vue控制了跳转)
// shiroFilterFactoryBean.setSuccessUrl("/index");
// 设置没有权限时跳转的url
shiroFilterFactoryBean.setUnauthorizedUrl("/api/auth/unauth");
shiroFilterFactoryBean.setFilterChainDefinitionMap( shiroConfig.loadFilterChainDefinitionMap() );
return shiroFilterFactoryBean;
}
/**
* 安全管理器
*/
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 自定义session管理
securityManager.setSessionManager(sessionManager());
// 自定义Cache实现缓存管理
securityManager.setCacheManager(cacheManager());
// 自定义Realm验证
securityManager.setRealm(shiroRealm());
return securityManager;
}
/**
* 身份验证器
*/
@Bean
public ShiroRealm shiroRealm() {
ShiroRealm shiroRealm = new ShiroRealm();
shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return shiroRealm;
}
/**
* 自定义Realm的加密规则 -> 凭证匹配器:将密码校验交给Shiro的SimpleAuthenticationInfo进行处理,在这里做匹配配置
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
// 散列算法:这里使用SHA256算法;
shaCredentialsMatcher.setHashAlgorithmName(SHA256Util.HASH_ALGORITHM_NAME);
// 散列的次数,比如散列两次,相当于 md5(md5(""));
shaCredentialsMatcher.setHashIterations(SHA256Util.HASH_ITERATIONS);
return shaCredentialsMatcher;
}
/**
* 配置Redis管理器:使用的是shiro-redis开源插件
*/
@Bean
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPort(port);
redisManager.setTimeout(timeout);
// redisManager.setPassword(password);
return redisManager;
}
/**
* 配置Cache管理器:用于往Redis存储权限和角色标识 (使用的是shiro-redis开源插件)
*/
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
redisCacheManager.setKeyPrefix(CACHE_KEY);
// 配置缓存的话要求放在session里面的实体类必须有个id标识 注:这里id为用户表中的主键,否-> 报:User must has getter for field: xx
redisCacheManager.setPrincipalIdFieldName("id");
return redisCacheManager;
}
/**
* SessionID生成器
*/
@Bean
public ShiroSessionIdGenerator sessionIdGenerator(){
return new ShiroSessionIdGenerator();
}
/**
* 配置RedisSessionDAO (使用的是shiro-redis开源插件)
*/
@Bean
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
redisSessionDAO.setSessionIdGenerator(sessionIdGenerator());
redisSessionDAO.setKeyPrefix(SESSION_KEY);
redisSessionDAO.setExpire(EXPIRE);
return redisSessionDAO;
}
/**
* 配置Session管理器
*/
@Bean
public SessionManager sessionManager() {
ShiroSessionManager shiroSessionManager = new ShiroSessionManager();
shiroSessionManager.setSessionDAO(redisSessionDAO());
return shiroSessionManager;
}
}
loadFilterChainDefinitionMap
:初始化权限ShiroConfig
中的Shiro基础配置shiroFilterFactory
方法中我们就需要调用此方法将数据库中配置的所有uri权限全部加载进去,以及放行接口和配置权限过滤器等【注:过滤器配置顺序不能颠倒,多个过滤器用
,分割】
filterChainDefinitionMap.put("/api/system/user/list", "authc,token,zqPerms[user1]")
updatePermission
:动态刷新加载数据库中的uri权限 -> 页面在新增uri路径到数据库中,也就是配置新的权限时就可以调用此方法实现动态加载uri权限updatePermissionByRoleId
:shiro动态权限加载 -> 即分配指定用户权限时可调用此方法删除shiro缓存,重新执行doGetAuthorizationInfo
方法授权角色和权限public interface ShiroService {
/**
* 初始化权限 -> 拿全部权限
*
* @param :
* @return: java.util.Map
*/
Map loadFilterChainDefinitionMap();
/**
* 在对uri权限进行增删改操作时,需要调用此方法进行动态刷新加载数据库中的uri权限
*
* @param shiroFilterFactoryBean
* @param roleId
* @param isRemoveSession:
* @return: void
*/
void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession);
/**
* shiro动态权限加载 -> 原理:删除shiro缓存,重新执行doGetAuthorizationInfo方法授权角色和权限
*
* @param roleId
* @param isRemoveSession:
* @return: void
*/
void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession);
}
@Slf4j
@Service
public class ShiroServiceImpl implements ShiroService {
@Autowired
private MenuMapper menuMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public Map loadFilterChainDefinitionMap() {
// 权限控制map
Map filterChainDefinitionMap = new LinkedHashMap<>();
// 配置过滤:不会被拦截的链接 -> 放行 start ----------------------------------------------------------
// 放行Swagger2页面,需要放行这些
filterChainDefinitionMap.put("/swagger-ui.html","anon");
filterChainDefinitionMap.put("/swagger/**","anon");
filterChainDefinitionMap.put("/webjars/**", "anon");
filterChainDefinitionMap.put("/swagger-resources/**","anon");
filterChainDefinitionMap.put("/v2/**","anon");
filterChainDefinitionMap.put("/static/**", "anon");
// 登陆
filterChainDefinitionMap.put("/api/auth/login/**", "anon");
// 三方登录
filterChainDefinitionMap.put("/api/auth/loginByQQ", "anon");
filterChainDefinitionMap.put("/api/auth/afterlogin.do", "anon");
// 退出
filterChainDefinitionMap.put("/api/auth/logout", "anon");
// 放行未授权接口,重定向使用
filterChainDefinitionMap.put("/api/auth/unauth", "anon");
// token过期接口
filterChainDefinitionMap.put("/api/auth/tokenExpired", "anon");
// 被挤下线
filterChainDefinitionMap.put("/api/auth/downline", "anon");
// 放行 end ----------------------------------------------------------
// 从数据库或缓存中查取出来的url与resources对应则不会被拦截 放行
List
zqPerms
@Slf4j
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String requestUrl = httpRequest.getServletPath();
log.info("请求的url: " + requestUrl);
// 检查是否拥有访问权限
Subject subject = this.getSubject(request, response);
if (subject.getPrincipal() == null) {
this.saveRequestAndRedirectToLogin(request, response);
} else {
// 转换成http的请求和响应
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 获取请求头的值
String header = req.getHeader("X-Requested-With");
// ajax 的请求头里有X-Requested-With: XMLHttpRequest 正常请求没有
if (header!=null && "XMLHttpRequest".equals(header)){
resp.setContentType("text/json,charset=UTF-8");
resp.getWriter().print("{\"success\":false,\"msg\":\"没有权限操作!\"}");
}else { //正常请求
String unauthorizedUrl = this.getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}
}
return false;
}
}
zqRoles
shiro原生的角色过滤器RolesAuthorizationFilter 默认是必须同时满足roles[admin,guest]
才有权限,而自定义的zqRoles
只满足其中一个即可访问
ex: zqRoles[admin,guest]
public class MyRolesAuthorizationFilter extends AuthorizationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {
Subject subject = getSubject(req, resp);
String[] rolesArray = (String[]) mappedValue;
// 没有角色限制,有权限访问
if (rolesArray == null || rolesArray.length == 0) {
return true;
}
for (int i = 0; i < rolesArray.length; i++) {
//若当前用户是rolesArray中的任何一个,则有权限访问
if (subject.hasRole(rolesArray[i])) {
return true;
}
}
return false;
}
}
token
-> 判断token是否过期失效等@Slf4j
public class TokenCheckFilter extends UserFilter {
/**
* token过期、失效
*/
private static final String TOKEN_EXPIRED_URL = "/api/auth/tokenExpired";
/**
* 判断是否拥有权限 true:认证成功 false:认证失败
* mappedValue 访问该url时需要的权限
* subject.isPermitted 判断访问的用户是否拥有mappedValue权限
*/
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 根据请求头拿到token
String token = WebUtils.toHttp(request).getHeader(Constants.REQUEST_HEADER);
log.info("浏览器token:" + token );
User userInfo = ShiroUtils.getUserInfo();
String userToken = userInfo.getToken();
// 检查token是否过期
if ( !token.equals(userToken) ){
return false;
}
return true;
}
/**
* 认证失败回调的方法: 如果登录实体为null就保存请求和跳转登录页面,否则就跳转无权限配置页面
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
User userInfo = ShiroUtils.getUserInfo();
// 重定向错误提示处理 - 前后端分离情况下
WebUtils.issueRedirect(request, response, TOKEN_EXPIRED_URL);
return false;
}
}
温馨小提示:这里只是部分,详情可参考文章末尾给出的案例demo源码
public class ShiroUtils {
/** 私有构造器 **/
private ShiroUtils(){ }
private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class);
/**
* 获取当前用户Session
* @Return SysUserEntity 用户信息
*/
public static Session getSession() {
return SecurityUtils.getSubject().getSession();
}
/**
* 用户登出
*/
public static void logout() {
SecurityUtils.getSubject().logout();
}
/**
* 获取当前用户信息
* @Return SysUserEntity 用户信息
*/
public static User getUserInfo() {
return (User) SecurityUtils.getSubject().getPrincipal();
}
/**
* 删除用户缓存信息
* @Param username 用户名称
* @Param isRemoveSession 是否删除Session,删除后用户需重新登录
*/
public static void deleteCache(String username, boolean isRemoveSession){
//从缓存中获取Session
Session session = null;
// 获取当前已登录的用户session列表
Collection sessions = redisSessionDAO.getActiveSessions();
User sysUserEntity;
Object attribute = null;
// 遍历Session,找到该用户名称对应的Session
for(Session sessionInfo : sessions){
attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (attribute == null) {
continue;
}
sysUserEntity = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
if (sysUserEntity == null) {
continue;
}
if (Objects.equals(sysUserEntity.getUsername(), username)) {
session=sessionInfo;
// 清除该用户以前登录时保存的session,强制退出 -> 单用户登录处理
if (isRemoveSession) {
redisSessionDAO.delete(session);
}
}
}
if (session == null||attribute == null) {
return;
}
//删除session
if (isRemoveSession) {
redisSessionDAO.delete(session);
}
//删除Cache,再访问受限接口时会重新授权
DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
Authenticator authc = securityManager.getAuthenticator();
((LogoutAware) authc).onLogout((SimplePrincipalCollection) attribute);
}
/**
* 从缓存中获取指定用户名的Session
* @param username
*/
private static Session getSessionByUsername(String username){
// 获取当前已登录的用户session列表
Collection sessions = redisSessionDAO.getActiveSessions();
User user;
Object attribute;
// 遍历Session,找到该用户名称对应的Session
for(Session session : sessions){
attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (attribute == null) {
continue;
}
user = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();
if (user == null) {
continue;
}
if (Objects.equals(user.getUsername(), username)) {
return session;
}
}
return null;
}
}
public interface RedisConstant {
/**
* TOKEN前缀
*/
String REDIS_PREFIX_LOGIN = "code-generator_token_%s";
}
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext context;
/**
* Spring在bean初始化后会判断是不是ApplicationContextAware的子类
* 如果该类是,setApplicationContext()方法,会将容器中ApplicationContext作为参数传入进去
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
/**
* 通过Name返回指定的Bean
*/
public static T getBean(Class beanClass) {
return context.getBean(beanClass);
}
}
https://github.com/zhengqingya/code-generator/tree/master/code-generator-api/src/main/java/com/zhengqing/modules/shiro
https://gitee.com/zhengqingya/code-generator/blob/master/code-generator-api/src/main/java/com/zhengqing/modules/shiro