您好,登錄后才能下訂單哦!
本篇內容介紹了“shiro的配置和使用方法”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
jar:
<shiro.version>1.2.3</shiro.version>
<!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency>
自定義自定義Realm:
import com.xmdishi.fmp.model.po.business.BusinessMenuPo; import com.xmdishi.fmp.model.po.business.BusinessUserPo; import com.xmdishi.fmp.model.qo.business.BusinessUserQo; import com.xmdishi.fmp.service.business.BusinessMenuService; import com.xmdishi.fmp.service.business.BusinessUserService; import org.apache.shiro.authc.*; import org.apache.shiro.authc.credential.CredentialsMatcher; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 自定義Realm * @author cjianquan * @date 2020/4/6 * @param * @return */ @Component public class CustomRealm extends AuthorizingRealm { @Autowired private BusinessUserService businessUserService; @Autowired private BusinessMenuService businessMenuService; private static Logger logger=LoggerFactory.getLogger(CustomRealm.class); public CustomRealm() { logger.info("CustomRealm===================="); } @Override public String getName() { return "CustomRealm"; } @Bean(name = "credentialsMatcher") public HashedCredentialsMatcher credentialsMatcher(){ HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); credentialsMatcher.setHashAlgorithmName("md5"); credentialsMatcher.setHashIterations(1); return credentialsMatcher; } @Override public void setCredentialsMatcher(@Qualifier("credentialsMatcher")CredentialsMatcher credentialsMatcher){ super.setCredentialsMatcher(credentialsMatcher); } /** * realm授權方法 從輸入參數principalCollection得到身份信息 根據身份信息到數據庫查找權限信息 將權限信息添加給授權信息對象 * 返回 授權信息對象(判斷用戶訪問url是否在權限信息中沒有體現) */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { BusinessUserPo user = (BusinessUserPo) principalCollection.getPrimaryPrincipal(); String roleIds = user.getRoleIds(); List<String> btnList = null; try{ btnList = businessMenuService.queryBtnsByRoles(roleIds); }catch (Exception e){ e.printStackTrace(); } // 用戶權限列表 Set<String> permsSet = new HashSet<String>(); if(btnList!=null && btnList.size()>0){ permsSet.addAll(btnList); } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.setStringPermissions(permsSet); return info; } /** * 表單認證過濾器認證時會調用自定義Realm的認證方法進行認證,成功回到index.do,再跳轉到index.jsp頁面 * * 前提:表單認證過濾器收集和組織用戶名和密碼信息封裝為token對象傳遞給此方法 * * token:封裝了身份信息和憑證信息 2步驟:比對身份 信息;比對憑證 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); // 查詢用戶信息 BusinessUserQo userQo = new BusinessUserQo(); userQo.setUserName(username); List<BusinessUserPo> userList = null; BusinessUserPo businessUserPo = null; try{ userList = this.businessUserService.query(userQo); if(userList!=null && userList.size()>0){ businessUserPo = userList.get(0); } }catch (Exception e){ e.printStackTrace(); } // 賬號不存在 if (businessUserPo == null ) { throw new UnknownAccountException("賬號不存在!"); } // 密碼錯誤 if (!password.equals(businessUserPo.getPassword())) { throw new IncorrectCredentialsException("賬號或密碼不正確!"); } // 賬號未分配角色 if (businessUserPo.getRoleIds() == null ) { throw new UnknownAccountException("賬號未分配角色!"); } //cjianquan 2020/2/8 登錄成功,查詢菜單 try{ List<BusinessMenuPo> menuList = this.businessMenuService.queryByRoles(businessUserPo.getRoleIds()); businessUserPo.setMenuList(menuList); }catch (Exception e){ e.printStackTrace(); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(businessUserPo, password, getName()); return info; } }
web.xml 添加 :
<filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> <!-- targetBeanName??spring?shiro??????bean?id??? --> <init-param> <param-name>targetBeanName</param-name> <param-value>shiroFilter</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <!-- ????url???shiro?????? --> <url-pattern>/*</url-pattern> </filter-mapping>
SpringShiroConfig:
import com.xmdishi.fmp.business.shiro.CustomRealm; import org.apache.shiro.cache.ehcache.EhCacheManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.MethodInvokingFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class SpringShiroConfig { @Autowired private CustomRealm realm; public SpringShiroConfig() { System.out.println("SpringShiroConfig init ......"); } @Bean(name = "lifecycleBeanPostProcessor") public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean @DependsOn("lifecycleBeanPostProcessor") public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); creator.setProxyTargetClass(true); creator.setUsePrefix(true); return creator; } @Bean public MethodInvokingFactoryBean getMethodInvokingFactoryBean(@Qualifier("securityManager")SecurityManager securityManager) { MethodInvokingFactoryBean methodInvokingFactoryBean=new MethodInvokingFactoryBean(); methodInvokingFactoryBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager"); methodInvokingFactoryBean.setArguments(new Object[]{securityManager}); return methodInvokingFactoryBean; } //get @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager")SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } //get @Bean(name = "shiroFilter") public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")SecurityManager securityManager){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setLoginUrl("/index.jsp"); shiroFilterFactoryBean.setSuccessUrl("/index.jsp"); shiroFilterFactoryBean.setUnauthorizedUrl("/index.jsp"); shiroFilterFactoryBean.setSecurityManager(securityManager); loadShiroFilterChain(shiroFilterFactoryBean); return shiroFilterFactoryBean; } //get @Bean(name = "sessionManager") public DefaultWebSessionManager sessionManager(){ DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setGlobalSessionTimeout(86400000); sessionManager.setDeleteInvalidSessions(true); return sessionManager; } //get @Bean(name = "shiroCacheManager") public EhCacheManager shiroCacheManager(){ EhCacheManager shiroCacheManager = new EhCacheManager(); shiroCacheManager.setCacheManagerConfigFile("classpath:shiro-ehcache.xml"); return shiroCacheManager; } //get @Bean(name = "securityManager") public DefaultWebSecurityManager securityManager(@Qualifier("shiroCacheManager") EhCacheManager shiroCacheManager, @Qualifier("sessionManager") DefaultWebSessionManager sessionManager) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(realm); securityManager.setCacheManager(shiroCacheManager); securityManager.setSessionManager(sessionManager); return securityManager; } //get private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean) { Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); filterChainDefinitionMap.put("/index.jsp", "anon"); filterChainDefinitionMap.put("/common/**", "anon"); filterChainDefinitionMap.put("/**/login/**", "anon"); filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); } }
登錄方法:
@RequestMapping(value = "login") @ResponseBody public Object login(@ModelAttribute("user")LoginUser user, HttpServletRequest request) { BaseResp resp = new BaseResp(); String access_token = ""+ IdUtils.id(); JSONObject jsonObject = new JSONObject(); /** * 使用Shiro編寫認證操作 */ try { //1.獲取Subject Subject subject = SecurityUtils.getSubject(); //2.封裝用戶數據 UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), CommonUtils.md5(user.getPassword())); // UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword()); //3.執行登錄方法 subject.login(token); jsonObject.put("access_token",access_token); jsonObject.put("user",rtnUser((BusinessUserPo)subject.getPrincipal())); resp.setData(jsonObject); } catch (UnknownAccountException e) { resp.setSuccess(false); resp.setMsg(e.getMessage()); e.printStackTrace(); } catch (IncorrectCredentialsException e) { resp.setSuccess(false); resp.setMsg(e.getMessage()); e.printStackTrace(); }catch (Exception e){ resp.setSuccess(false); resp.setMsg("系統異常,請稍后再試"); e.printStackTrace(); } return resp; }
前臺頁面使用: jsp:
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
按鈕權限:
<div class="layui-btn-container"> <shiro:hasPermission name="taskProgress:add"> <button class="layui-btn layui-btn-sm" data-type="addRec">添加</button> </shiro:hasPermission> <shiro:hasPermission name="taskProgress:del"> <button class="layui-btn layui-btn-sm layui-btn-danger" data-type="delRec">刪除</button> </shiro:hasPermission> </div>
“shiro的配置和使用方法”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。