In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "the configuration and use of shiro". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Jar:
1.2.3 org.apache.shiro shiro-core ${shiro.version} org.apache.shiro shiro-ehcache ${shiro.version} org.apache.shiro shiro-web ${shiro.version} org.apache.shiro shiro-spring ${shiro.version}
Custom 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 / * * Custom Realm * @ author cjianquan * @ date 2020-4-6 * @ param * @ return * / @ Componentpublic 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) } / * the realm authorization method obtains the identity information from the input parameter principalCollection and adds the permission information to the authorization information object according to the identity information to the database to find permission information. * returns the authorization information object (to determine whether the user's access to url is not reflected in the permission information) * / @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {BusinessUserPo user = (BusinessUserPo) principalCollection.getPrimaryPrincipal () String roleIds = user.getRoleIds (); List btnList = null; try {btnList = businessMenuService.queryBtnsByRoles (roleIds);} catch (Exception e) {e.printStackTrace ();} / / user rights list Set permsSet = new HashSet (); if (btnListlist null & & btnList.size () > 0) {permsSet.addAll (btnList);} SimpleAuthorizationInfo info = new SimpleAuthorizationInfo () Info.setStringPermissions (permsSet); return info } / * form authentication filter will call the authentication method of custom Realm for authentication, successfully return to index.do, and then jump to the index.jsp page * * premise: form authentication filter collects and organizes user name and password information encapsulated as token object and passes it to this method * * token: encapsulates identity information and credential information 2 steps: compare identity information Compare credentials * / @ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {String username = (String) token.getPrincipal (); String password = new String ((char []) token.getCredentials ()); / / query user information BusinessUserQo userQo = new BusinessUserQo (); userQo.setUserName (username); List userList = null; BusinessUserPo businessUserPo = null; try {userList = this.businessUserService.query (userQo) If {businessUserPo = userList.get (0);}} catch (Exception e) {e.printStackTrace ();} / / if (businessUserPo = = null) {throw new UnknownAccountException ("account does not exist!") } / / incorrect password if (! password.equals (businessUserPo.getPassword () {throw new IncorrectCredentialsException ("account or password is incorrect!");} / / account unassigned role if (businessUserPo.getRoleIds () = = null) {throw new UnknownAccountException ("account is not assigned a role!") } / / cjianquan successfully logged in on 2020-2-8. Query menu try {List 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 add:
ShiroFilter org.springframework.web.filter.DelegatingFilterProxy targetFilterLifecycle true targetBeanName shiroFilter shiroFilter / *
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;@Configurationpublic 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 filterChainDefinitionMap = new LinkedHashMap (); filterChainDefinitionMap.put ("/ index.jsp", "anon"); filterChainDefinitionMap.put ("/ common/**", "anon"); filterChainDefinitionMap.put ("/ * / login/**", "anon"); filterChainDefinitionMap.put ("/ * *", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap (filterChainDefinitionMap);}}
Login method:
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 (); / * * use Shiro to write authentication operations * / try {/ / 1. Get Subject Subject subject = SecurityUtils.getSubject (); / / 2. Encapsulate user data UsernamePasswordToken token = new UsernamePasswordToken (user.getUserName (), CommonUtils.md5 (user.getPassword (); / / UsernamePasswordToken token = new UsernamePasswordToken (user.getUserName (), user.getPassword ()); / / 3. Execute login method 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 ("system exception, please try again later"); e.printStackTrace () } return resp;}
The front page uses: jsp:
Button permissions:
This is the end of adding and deleting the content of "configuration and use of shiro". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.