您好,登錄后才能下訂單哦!
小編給大家分享一下SpringBoot2如何整合Shiro框架實(shí)現(xiàn)用戶權(quán)限管理,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
Apache Shiro是一個(gè)強(qiáng)大且易用的Java安全框架,執(zhí)行身份驗(yàn)證、授權(quán)、密碼和會(huì)話管理。作為一款安全框架Shiro的設(shè)計(jì)相當(dāng)巧妙。Shiro的應(yīng)用不依賴任何容器,它不僅可以在JavaEE下使用,還可以應(yīng)用在JavaSE環(huán)境中。
1)Subject:認(rèn)證主體
代表當(dāng)前系統(tǒng)的使用者,就是用戶,在Shiro的認(rèn)證中,認(rèn)證主體通常就是userName和passWord,或者其他用戶相關(guān)的唯一標(biāo)識(shí)。
2)SecurityManager:安全管理器
Shiro架構(gòu)中最核心的組件,通過它可以協(xié)調(diào)其他組件完成用戶認(rèn)證和授權(quán)。實(shí)際上,SecurityManager就是Shiro框架的控制器。
3)Realm:域?qū)ο?/p>
定義了訪問數(shù)據(jù)的方式,用來連接不同的數(shù)據(jù)源,如:關(guān)系數(shù)據(jù)庫(kù),配置文件等等。
Shiro自己不維護(hù)用戶和權(quán)限,通過Subject用戶主體和Realm域?qū)ο蟮淖⑷耄瓿捎脩舻恼J(rèn)證和授權(quán)。
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency>
@Configuration public class ShiroConfig { /** * Session Manager:會(huì)話管理 * 即用戶登錄后就是一次會(huì)話,在沒有退出之前,它的所有信息都在會(huì)話中; * 會(huì)話可以是普通JavaSE環(huán)境的,也可以是如Web環(huán)境的; */ @Bean("sessionManager") public SessionManager sessionManager(){ DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); //設(shè)置session過期時(shí)間 sessionManager.setGlobalSessionTimeout(60 * 60 * 1000); sessionManager.setSessionValidationSchedulerEnabled(true); // 去掉shiro登錄時(shí)url里的JSESSIONID sessionManager.setSessionIdUrlRewritingEnabled(false); return sessionManager; } /** * SecurityManager:安全管理器 */ @Bean("securityManager") public SecurityManager securityManager(UserRealm userRealm, SessionManager sessionManager) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setSessionManager(sessionManager); securityManager.setRealm(userRealm); return securityManager; } /** * ShiroFilter是整個(gè)Shiro的入口點(diǎn),用于攔截需要安全控制的請(qǐng)求進(jìn)行處理 */ @Bean("shiroFilter") public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); shiroFilter.setSecurityManager(securityManager); shiroFilter.setLoginUrl("/userLogin"); shiroFilter.setUnauthorizedUrl("/"); Map<String, String> filterMap = new LinkedHashMap<>(); filterMap.put("/userLogin", "anon"); shiroFilter.setFilterChainDefinitionMap(filterMap); return shiroFilter; } /** * 管理Shiro中一些bean的生命周期 */ @Bean("lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } /** * 掃描上下文,尋找所有的Advistor(通知器) * 將這些Advisor應(yīng)用到所有符合切入點(diǎn)的Bean中。 */ @Bean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator(); proxyCreator.setProxyTargetClass(true); return proxyCreator; } /** * 匹配所有加了 Shiro 認(rèn)證注解的方法 */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; } }
@Component public class UserRealm extends AuthorizingRealm { @Resource private SysUserMapper sysUserMapper ; @Resource private SysMenuMapper sysMenuMapper ; /** * 授權(quán)(驗(yàn)證權(quán)限時(shí)調(diào)用) * 獲取用戶權(quán)限集合 */ @Override public AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) { SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal(); if(user == null) { throw new UnknownAccountException("賬號(hào)不存在"); } List<String> permsList; //默認(rèn)用戶擁有最高權(quán)限 List<SysMenuEntity> menuList = sysMenuMapper.selectList(); permsList = new ArrayList<>(menuList.size()); for(SysMenuEntity menu : menuList){ permsList.add(menu.getPerms()); } //用戶權(quán)限列表 Set<String> permsSet = new HashSet<>(); for(String perms : permsList){ if(StringUtils.isEmpty(perms)){ continue; } permsSet.addAll(Arrays.asList(perms.trim().split(","))); } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.setStringPermissions(permsSet); return info; } /** * 認(rèn)證(登錄時(shí)調(diào)用) * 驗(yàn)證用戶登錄 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken)authToken; //查詢用戶信息 SysUserEntity user = sysUserMapper.selectOne(token.getUsername()); //賬號(hào)不存在 if(user == null) { throw new UnknownAccountException("賬號(hào)或密碼不正確"); } //賬號(hào)鎖定 if(user.getStatus() == 0){ throw new LockedAccountException("賬號(hào)已被鎖定,請(qǐng)聯(lián)系管理員"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo (user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName()); return info; } @Override public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) { HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher(); shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName); shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations); super.setCredentialsMatcher(shaCredentialsMatcher); } }
public class ShiroUtils { /** 加密算法 */ public final static String hashAlgorithmName = "SHA-256"; /** 循環(huán)次數(shù) */ public final static int hashIterations = 16; public static String sha256(String password, String salt) { return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString(); } // 獲取一個(gè)測(cè)試賬號(hào) admin public static void main(String[] args) { // 3743a4c09a17e6f2829febd09ca54e627810001cf255ddcae9dabd288a949c4a System.out.println(sha256("admin","123")) ; } /** * 獲取會(huì)話 */ public static Session getSession() { return SecurityUtils.getSubject().getSession(); } /** * Subject:主體,代表了當(dāng)前“用戶” */ public static Subject getSubject() { return SecurityUtils.getSubject(); } public static SysUserEntity getUserEntity() { return (SysUserEntity)SecurityUtils.getSubject().getPrincipal(); } public static Long getUserId() { return getUserEntity().getUserId(); } public static void setSessionAttribute(Object key, Object value) { getSession().setAttribute(key, value); } public static Object getSessionAttribute(Object key) { return getSession().getAttribute(key); } public static boolean isLogin() { return SecurityUtils.getSubject().getPrincipal() != null; } public static void logout() { SecurityUtils.getSubject().logout(); } }
@RestControllerAdvice public class ShiroException { @ExceptionHandler(AuthorizationException.class) public String authorizationException (){ return "抱歉您沒有權(quán)限訪問該內(nèi)容!"; } @ExceptionHandler(Exception.class) public String handleException(Exception e){ return "系統(tǒng)異常!"; } }
@RestController public class ShiroController { private static Logger LOGGER = LoggerFactory.getLogger(ShiroController.class) ; @Resource private SysMenuMapper sysMenuMapper ; /** * 登錄測(cè)試 * http://localhost:7011/userLogin?userName=admin&passWord=admin */ @RequestMapping("/userLogin") public void userLogin ( @RequestParam(value = "userName") String userName, @RequestParam(value = "passWord") String passWord){ try{ Subject subject = ShiroUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord); subject.login(token); LOGGER.info("登錄成功"); }catch (Exception e) { e.printStackTrace(); } } /** * 服務(wù)器每次重啟請(qǐng)求該接口之前必須先請(qǐng)求上面登錄接口 * http://localhost:7011/menu/list 獲取所有菜單列表 * 權(quán)限要求:sys:user:shiro */ @RequestMapping("/menu/list") @RequiresPermissions("sys:user:shiro") public List list(){ return sysMenuMapper.selectList() ; } /** * 用戶沒有該權(quán)限,無法訪問 * 權(quán)限要求:ccc:ddd:bbb */ @RequestMapping("/menu/list2") @RequiresPermissions("ccc:ddd:bbb") public List list2(){ return sysMenuMapper.selectList() ; } /** * 退出測(cè)試,退出后沒有任何權(quán)限 */ @RequestMapping("/userLogOut") public String logout (){ ShiroUtils.logout(); return "success" ; } }
1)、登錄后取得權(quán)限 http://localhost:7011/userLogin?userName=admin&passWord=admin 2)、訪問有權(quán)限接口 http://localhost:7011/menu/list 3)、訪問無權(quán)限接口 http://localhost:7011/menu/list2 4)、退出登錄 http://localhost:7011/userLogOut
以上是“SpringBoot2如何整合Shiro框架實(shí)現(xiàn)用戶權(quán)限管理”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。