SpringBoot Shiro授權實現過程解析
這篇文章主要介紹了SpringBoot Shiro授權實現過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
使用Shiro過濾器實現授權
設置好授權攔截跳轉的請求地址
/** * 創(chuàng)建ShiroFilterFactoryBean */ @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean(); //設置安全管理器 shiroFilterFactoryBean.setSecurityManager(securityManager); //添加Shiro內置過濾器 /** * Shiro內置過濾器,可以實現權限相關的攔截器 * 常用的過濾器: * anon:無需認證(登錄)可以訪問 * authc:必須認證才可以訪問 * user:如果使用rememberMe的功能可以直接訪問 * perms:該資源必須得到資源權限才可以訪問 * role:該資源必須得到角色權限才可以訪問 */ Map<String, String> filterMap= new LinkedHashMap<String,String>(); //設置攔截后跳轉的請求路徑 shiroFilterFactoryBean.setLoginUrl("/user/badRequest"); //設置未授權提示的頁面 shiroFilterFactoryBean.setUnauthorizedUrl("/user/badRequest"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap); return shiroFilterFactoryBean; }
再使用 filterMap 去放對應的攔截即可,例如 filterMap.put("/**", "anon")
上面是認證的,如果需要授權的,相應的多給一個任意的授權字符串如 filterMap.put("/user/add", "perms[user:add]")
授權邏輯編寫的位置
/** * 執(zhí)行授權邏輯 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { System.out.println("開始執(zhí)行Shiro的授權方法..."); //給資源進行授權 SimpleAuthorizationInfo info= new SimpleAuthorizationInfo(); //添加資源的授權字符串 info.addStringPermission("user:add"); return null; }
授權字符串和之前的字符串對應
補充
/** * 執(zhí)行認證邏輯 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException { System.out.println("開始執(zhí)行Shiro的認證方法..."); //編寫Shiro判斷邏輯,判斷用戶名和密碼 //判斷用戶名是否存在 UsernamePasswordToken token=(UsernamePasswordToken)arg0; User user = userMapper.findByUsername(token.getUsername()); if(user==null) return null; //判斷密碼是否正確,參數一為認證的實體 return new SimpleAuthenticationInfo(user,user.getPassword(),""); }
在執(zhí)行認證時的SimpleAuthenticationInfo第一個傳參可以用來獲取當前用戶
/** * 執(zhí)行授權邏輯 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { System.out.println("開始執(zhí)行Shiro的授權方法..."); //給資源進行授權 SimpleAuthorizationInfo info= new SimpleAuthorizationInfo(); //添加資源的授權字符串 info.addStringPermission("user:register"); //獲取當前的登錄用戶 User user=(User)SecurityUtils.getSubject().getPrincipal(); return null; }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
基于springboot redirect重定向路徑問題總結
這篇文章主要介紹了springboot redirect重定向路徑問題總結,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09解決MyBatis中模糊搜索使用like匹配帶%字符時失效問題
Mybatis是我們日常項目中經常使用的框架,在項目中我們一般會使用like查詢作為模糊匹配字符進行搜索匹配,下面的Mapper.xml是我們使用like在項目中進行模糊匹配的常用方式,感興趣的朋友跟隨小編一起看看吧2021-09-09