一、前言
本文小编将基于 SpringBoot 集成 Shiro 实现动态uri权限,由前端vue在页面配置uri,Java后端动态刷新权限,不用重启项目,以及在页面分配给用户 角色 、 按钮 、uri 权限后,后端动态分配权限,用户无需在页面重新登录才能获取最新权限,一切权限动态加载,灵活配置
基本环境
- spring-boot 2.1.7
- mybatis-plus 2.1.0
- mysql 5.7.24
- redis 5.0.5
温馨小提示:案例demo源码附文章末尾,有需要的小伙伴们可参考哦 ~
二、SpringBoot集成Shiro
1、引入相关maven依赖
1.4.0 3.1.0 org.springframework.boot spring-boot-starter-aoporg.springframework.boot spring-boot-starter-data-redis-reactiveorg.apache.shiro shiro-spring${shiro-spring.version} org.crazycake shiro-redis${shiro-redis.version}
2、自定义Realm
- 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";
}
@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
3、Shiro配置类
@Configuration
public class ShiroConfig {
private final String CACHE_KEY = "shiro:cache:";
private final String SESSION_KEY = "shiro:session:";
private final int EXPIRE = 1800;
@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;
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
@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;
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
// 散列算法:这里使用SHA256算法;
shaCredentialsMatcher.setHashAlgorithmName(SHA256Util.HASH_ALGORITHM_NAME);
// 散列的次数,比如散列两次,相当于 md5(md5(""));
shaCredentialsMatcher.setHashIterations(SHA256Util.HASH_ITERATIONS);
return shaCredentialsMatcher;
}
@Bean
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPort(port);
redisManager.setTimeout(timeout);
// redisManager.setPassword(password);
return redisManager;
}
@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;
}
@Bean
public ShiroSessionIdGenerator sessionIdGenerator(){
return new ShiroSessionIdGenerator();
}
@Bean
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
redisSessionDAO.setSessionIdGenerator(sessionIdGenerator());
redisSessionDAO.setKeyPrefix(SESSION_KEY);
redisSessionDAO.setExpire(EXPIRE);
return redisSessionDAO;
}
@Bean
public SessionManager sessionManager() {
ShiroSessionManager shiroSessionManager = new ShiroSessionManager();
shiroSessionManager.setSessionDAO(redisSessionDAO());
return shiroSessionManager;
}
}
三、shiro动态加载权限处理方法
- loadFilterChainDefinitionMap:初始化权限
ex: 在上面Shiro配置类ShiroConfig中的Shiro基础配置shiroFilterFactory方法中我们就需要调用此方法将数据库中配置的所有uri权限全部加载进去,以及放行接口和配置权限过滤器等
【注:过滤器配置顺序不能颠倒,多个过滤器用,分割】
ex: filterChainDefinitionMap.put("/api/system/user/list", "authc,token,zqPerms[user1]") - updatePermission:动态刷新加载数据库中的uri权限 -> 页面在新增uri路径到数据库中,也就是配置新的权限时就可以调用此方法实现动态加载uri权限
- updatePermissionByRoleId:shiro动态权限加载 -> 即分配指定用户权限时可调用此方法删除shiro缓存,重新执行doGetAuthorizationInfo方法授权角色和权限
public interface ShiroService {
Map loadFilterChainDefinitionMap();
void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession);
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
private static final String TOKEN_EXPIRED_URL = "/api/auth/tokenExpired";
@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;
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
User userInfo = ShiroUtils.getUserInfo();
// 重定向错误提示处理 - 前后端分离情况下
WebUtils.issueRedirect(request, response, TOKEN_EXPIRED_URL);
return false;
}
}
五、项目中会用到的一些工具类、常量等
温馨小提示:这里只是部分,详情可参考文章末尾给出的案例demo源码
1、Shiro工具类
public class ShiroUtils {
private ShiroUtils(){ }
private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class);
public static Session getSession() {
return SecurityUtils.getSubject().getSession();
}
public static void logout() {
SecurityUtils.getSubject().logout();
}
public static User getUserInfo() {
return (User) SecurityUtils.getSubject().getPrincipal();
}
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);
}
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;
}
}
2、Redis常量类
public interface RedisConstant {
String REDIS_PREFIX_LOGIN = "code-generator_token_%s";
}
3、Spring上下文工具类
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static T getBean(Class beanClass) {
return context.getBean(beanClass);
}
}
六、案例demo源码
GitHub地址
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
本地下载
http://xiazai.jb51.net/201909/yuanma/code-generator(jb51net).rar
总结
以上就是我在处理客户端真实IP的方法,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对考高分网的支持。



