一、前言
創(chuàng)新互聯(lián)建站提供成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì),品牌網(wǎng)站建設(shè),廣告投放等致力于企業(yè)網(wǎng)站建設(shè)與公司網(wǎng)站制作,10余年的網(wǎng)站開發(fā)和建站經(jīng)驗(yàn),助力企業(yè)信息化建設(shè),成功案例突破1000多家,是您實(shí)現(xiàn)網(wǎng)站建設(shè)的好選擇.
本文小編將基于 SpringBoot 集成 Shiro 實(shí)現(xiàn)動(dòng)態(tài)uri權(quán)限,由前端vue在頁(yè)面配置uri,Java后端動(dòng)態(tài)刷新權(quán)限,不用重啟項(xiàng)目,以及在頁(yè)面分配給用戶 角色 、 按鈕 、uri 權(quán)限后,后端動(dòng)態(tài)分配權(quán)限,用戶無(wú)需在頁(yè)面重新登錄才能獲取最新權(quán)限,一切權(quán)限動(dòng)態(tài)加載,靈活配置
基本環(huán)境
溫馨小提示:案例demo源碼附文章末尾,有需要的小伙伴們可參考哦 ~
二、SpringBoot集成Shiro
1、引入相關(guān)maven依賴
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}
2、自定義Realm
@Slf4j public class ShiroRealm extends AuthorizingRealm { @Autowired private UserMapper userMapper; @Autowired private MenuMapper menuMapper; @Autowired private RoleMapper roleMapper; @Override public String getName() { return "shiroRealm"; } /** * 賦予角色和權(quán)限:用戶進(jìn)行權(quán)限驗(yàn)證時(shí) Shiro會(huì)去緩存中找,如果查不到數(shù)據(jù),會(huì)執(zhí)行這個(gè)方法去查權(quán)限,并放入緩存中 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); // 獲取用戶 User user = (User) principalCollection.getPrimaryPrincipal(); Integer userId =user.getId(); // 這里可以進(jìn)行授權(quán)和處理 SetrolesSet = new HashSet<>(); Set permsSet = new HashSet<>(); // 獲取當(dāng)前用戶對(duì)應(yīng)的權(quán)限(這里根據(jù)業(yè)務(wù)自行查詢) 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:"; /** * 默認(rèn)過期時(shí)間30分鐘,即在30分鐘內(nèi)不進(jìn)行操作則清空緩存信息,頁(yè)面即會(huì)提醒重新登錄 */ 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基礎(chǔ)配置 */ @Bean public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager, ShiroServiceImpl shiroConfig){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); // 自定義過濾器 MapfiltersMap = new LinkedHashMap<>(); // 定義過濾器名稱 【注:map里面key值對(duì)于的value要為authc才能使用自定義的過濾器】 filtersMap.put( "zqPerms", new MyPermissionsAuthorizationFilter() ); filtersMap.put( "zqRoles", new MyRolesAuthorizationFilter() ); filtersMap.put( "token", new TokenCheckFilter() ); shiroFilterFactoryBean.setFilters(filtersMap); // 登錄的路徑: 如果你沒有登錄則會(huì)跳到這個(gè)頁(yè)面中 - 如果沒有設(shè)置值則會(huì)默認(rèn)跳轉(zhuǎn)到工程根目錄下的"/login.jsp"頁(yè)面 或 "/login" 映射 shiroFilterFactoryBean.setLoginUrl("/api/auth/unLogin"); // 登錄成功后跳轉(zhuǎn)的主頁(yè)面 (這里沒用,前端vue控制了跳轉(zhuǎn)) // shiroFilterFactoryBean.setSuccessUrl("/index"); // 設(shè)置沒有權(quán)限時(shí)跳轉(zhuǎn)的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實(shí)現(xiàn)緩存管理 securityManager.setCacheManager(cacheManager()); // 自定義Realm驗(yàn)證 securityManager.setRealm(shiroRealm()); return securityManager; } /** * 身份驗(yàn)證器 */ @Bean public ShiroRealm shiroRealm() { ShiroRealm shiroRealm = new ShiroRealm(); shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return shiroRealm; } /** * 自定義Realm的加密規(guī)則 -> 憑證匹配器:將密碼校驗(yàn)交給Shiro的SimpleAuthenticationInfo進(jìn)行處理,在這里做匹配配置 */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher(); // 散列算法:這里使用SHA256算法; shaCredentialsMatcher.setHashAlgorithmName(SHA256Util.HASH_ALGORITHM_NAME); // 散列的次數(shù),比如散列兩次,相當(dāng)于 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存儲(chǔ)權(quán)限和角色標(biāo)識(shí) (使用的是shiro-redis開源插件) */ @Bean public RedisCacheManager cacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); redisCacheManager.setKeyPrefix(CACHE_KEY); // 配置緩存的話要求放在session里面的實(shí)體類必須有個(gè)id標(biāo)識(shí) 注:這里id為用戶表中的主鍵,否-> 報(bào):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; } }
三、shiro動(dòng)態(tài)加載權(quán)限處理方法
public interface ShiroService { /** * 初始化權(quán)限 -> 拿全部權(quán)限 * * @param : * @return: java.util.Map*/ Map loadFilterChainDefinitionMap(); /** * 在對(duì)uri權(quán)限進(jìn)行增刪改操作時(shí),需要調(diào)用此方法進(jìn)行動(dòng)態(tài)刷新加載數(shù)據(jù)庫(kù)中的uri權(quán)限 * * @param shiroFilterFactoryBean * @param roleId * @param isRemoveSession: * @return: void */ void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession); /** * shiro動(dòng)態(tài)權(quán)限加載 -> 原理:刪除shiro緩存,重新執(zhí)行doGetAuthorizationInfo方法授權(quán)角色和權(quán)限 * * @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 MaploadFilterChainDefinitionMap() { // 權(quán)限控制map Map filterChainDefinitionMap = new LinkedHashMap<>(); // 配置過濾:不會(huì)被攔截的鏈接 -> 放行 start ---------------------------------------------------------- // 放行Swagger2頁(yè)面,需要放行這些 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"); // 放行未授權(quán)接口,重定向使用 filterChainDefinitionMap.put("/api/auth/unauth", "anon"); // token過期接口 filterChainDefinitionMap.put("/api/auth/tokenExpired", "anon"); // 被擠下線 filterChainDefinitionMap.put("/api/auth/downline", "anon"); // 放行 end ---------------------------------------------------------- // 從數(shù)據(jù)庫(kù)或緩存中查取出來(lái)的url與resources對(duì)應(yīng)則不會(huì)被攔截 放行 List
四、shiro中自定義角色、權(quán)限過濾器
1、自定義uri權(quán)限過濾器 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("請(qǐng)求的url: " + requestUrl); // 檢查是否擁有訪問權(quán)限 Subject subject = this.getSubject(request, response); if (subject.getPrincipal() == null) { this.saveRequestAndRedirectToLogin(request, response); } else { // 轉(zhuǎn)換成http的請(qǐng)求和響應(yīng) HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; // 獲取請(qǐng)求頭的值 String header = req.getHeader("X-Requested-With"); // ajax 的請(qǐng)求頭里有X-Requested-With: XMLHttpRequest 正常請(qǐng)求沒有 if (header!=null && "XMLHttpRequest".equals(header)){ resp.setContentType("text/json,charset=UTF-8"); resp.getWriter().print("{\"success\":false,\"msg\":\"沒有權(quán)限操作!\"}"); }else { //正常請(qǐng)求 String unauthorizedUrl = this.getUnauthorizedUrl(); if (StringUtils.hasText(unauthorizedUrl)) { WebUtils.issueRedirect(request, response, unauthorizedUrl); } else { WebUtils.toHttp(response).sendError(401); } } } return false; } }
2、自定義角色權(quán)限過濾器 zqRoles
shiro原生的角色過濾器RolesAuthorizationFilter 默認(rèn)是必須同時(shí)滿足roles[admin,guest]才有權(quán)限,而自定義的zqRoles 只滿足其中一個(gè)即可訪問
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; // 沒有角色限制,有權(quán)限訪問 if (rolesArray == null || rolesArray.length == 0) { return true; } for (int i = 0; i < rolesArray.length; i++) { //若當(dāng)前用戶是rolesArray中的任何一個(gè),則有權(quán)限訪問 if (subject.hasRole(rolesArray[i])) { return true; } } return false; } }
3、自定義token過濾器 token -> 判斷token是否過期失效等
@Slf4j public class TokenCheckFilter extends UserFilter { /** * token過期、失效 */ private static final String TOKEN_EXPIRED_URL = "/api/auth/tokenExpired"; /** * 判斷是否擁有權(quán)限 true:認(rèn)證成功 false:認(rèn)證失敗 * mappedValue 訪問該url時(shí)需要的權(quán)限 * subject.isPermitted 判斷訪問的用戶是否擁有mappedValue權(quán)限 */ @Override public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; // 根據(jù)請(qǐng)求頭拿到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; } /** * 認(rèn)證失敗回調(diào)的方法: 如果登錄實(shí)體為null就保存請(qǐng)求和跳轉(zhuǎn)登錄頁(yè)面,否則就跳轉(zhuǎn)無(wú)權(quán)限配置頁(yè)面 */ @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException { User userInfo = ShiroUtils.getUserInfo(); // 重定向錯(cuò)誤提示處理 - 前后端分離情況下 WebUtils.issueRedirect(request, response, TOKEN_EXPIRED_URL); return false; } }
五、項(xiàng)目中會(huì)用到的一些工具類、常量等
溫馨小提示:這里只是部分,詳情可參考文章末尾給出的案例demo源碼
1、Shiro工具類
public class ShiroUtils { /** 私有構(gòu)造器 **/ private ShiroUtils(){ } private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class); /** * 獲取當(dāng)前用戶Session * @Return SysUserEntity 用戶信息 */ public static Session getSession() { return SecurityUtils.getSubject().getSession(); } /** * 用戶登出 */ public static void logout() { SecurityUtils.getSubject().logout(); } /** * 獲取當(dāng)前用戶信息 * @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; // 獲取當(dāng)前已登錄的用戶session列表 Collectionsessions = redisSessionDAO.getActiveSessions(); User sysUserEntity; Object attribute = null; // 遍歷Session,找到該用戶名稱對(duì)應(yīng)的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; // 清除該用戶以前登錄時(shí)保存的session,強(qiáng)制退出 -> 單用戶登錄處理 if (isRemoveSession) { redisSessionDAO.delete(session); } } } if (session == null||attribute == null) { return; } //刪除session if (isRemoveSession) { redisSessionDAO.delete(session); } //刪除Cache,再訪問受限接口時(shí)會(huì)重新授權(quán) DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager(); Authenticator authc = securityManager.getAuthenticator(); ((LogoutAware) authc).onLogout((SimplePrincipalCollection) attribute); } /** * 從緩存中獲取指定用戶名的Session * @param username */ private static Session getSessionByUsername(String username){ // 獲取當(dāng)前已登錄的用戶session列表 Collection sessions = redisSessionDAO.getActiveSessions(); User user; Object attribute; // 遍歷Session,找到該用戶名稱對(duì)應(yīng)的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 { /** * TOKEN前綴 */ String REDIS_PREFIX_LOGIN = "code-generator_token_%s"; }
3、Spring上下文工具類
@Component public class SpringUtil implements ApplicationContextAware { private static ApplicationContext context; /** * Spring在bean初始化后會(huì)判斷是不是ApplicationContextAware的子類 * 如果該類是,setApplicationContext()方法,會(huì)將容器中ApplicationContext作為參數(shù)傳入進(jìn)去 */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } /** * 通過Name返回指定的Bean */ public staticT 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
總結(jié)
以上就是我在處理客戶端真實(shí)IP的方法,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)創(chuàng)新互聯(lián)的支持。