Environmental SpringBoot2.0
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency>
ShiroConfig
import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { @Bean publicShirFilter ShiroFilterFactoryBean (the SecurityManager securityManager) { System.out.println ( "ShiroConfiguration.shirFilter ()" ); ShiroFilterFactoryBean shiroFilterFactoryBean = new new ShiroFilterFactoryBean (); shiroFilterFactoryBean.setSecurityManager (securityManager); // interceptor. The Map <String, String> = filterChainDefinitionMap new new a LinkedHashMap <String, String> (); // configuration will not be intercepted url order determined // configuration exit filter, wherein the specific exit code Shiro has been achieved for us filterChainDefinitionMap.put ( "/ dologin", " anon " ); filterChainDefinitionMap.put ("/ Zimbabwe Logout", "anon" ); // <- chain is defined by filtration, performed sequentially from top to bottom, generally / ** in the most lower -!>: This is a pit it, accidentally Code not so that; // <- authc: All url must be certified before they can access through; anon:! All url can have anonymous access -> filterChainDefinitionMap.put ( "/ **", "authc" ) ; // If you do not set a default will automatically find "/login.jsp" page under the Web project root shiroFilterFactoryBean.setLoginUrl ( "/ the Login" ); // login after a successful jump to the link shiroFilterFactoryBean.setSuccessUrl ( "/ index " ); // unauthorized interface; shiroFilterFactoryBean.setUnauthorizedUrl (" / unauthorized " ); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); returnshiroFilterFactoryBean; } / ** * certificate matcher * (due to our password verification processing to Shiro SimpleAuthenticationInfo a *) * @return * / @Bean public HashedCredentialsMatcher hashedCredentialsMatcher () { HashedCredentialsMatcher hashedCredentialsMatcher = new new HashedCredentialsMatcher (); hashedCredentialsMatcher .setHashAlgorithmName ( "MD5"); // hashing algorithm: MD5 algorithm used here; hashedCredentialsMatcher.setHashIterations (. 1); // number of hash, such as the two hash corresponds md5 (md5 ( "")) ; return hashedCredentialsMatcher; } @Bean public MyShiroRealm myShiroRealm () { MyShiroRealm myShiroRealm = new new MyShiroRealm (); myShiroRealm.setCredentialsMatcher (hashedCredentialsMatcher ()); return myShiroRealm; } @Bean public the SecurityManager securityManager () { DefaultWebSecurityManager securityManager = new new DefaultWebSecurityManager (); securityManager.setRealm (myShiroRealm () ); return securityManager; } / ** * open shiro aop annotation support. * use a proxy way; so it is necessary to open the code support; * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }
Customizing a MyShiroRealm
Import org.apache.shiro.authc *. ; Import org.apache.shiro.authz.AuthorizationInfo; Import org.apache.shiro.authz.SimpleAuthorizationInfo; Import org.apache.shiro.crypto.hash.SimpleHash; Import org.apache .shiro.realm.AuthorizingRealm; Import org.apache.shiro.subject.PrincipalCollection; public class MyShiroRealm the extends AuthorizingRealm { / * certification is mainly used for authentication, which means that validate user input account and password are correct. * / @Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken AuthenticationToken) throws{Of AuthenticationException // convert into AuthenticationToken UsernamePasswordToken UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) AuthenticationToken; // Get username String username = usernamePasswordToken.getUsername (); // The query information database username (UserService injection method and call) from the omitted / / user information acquired AuthenticationException decide whether to throw an exception here-coded iF (username.equals ( "Unknown" )) { the throw new new UnknownAccountException ( "user does not exist!" ); } iF (username.equals ( " Lock " )) { the throw new newLockedAccountException ( "user is locked!" ); } // construct and return AuthenticationInfo, usually SimpleAuthenticationInfo // Principal: can be a username, or a user entity object // Credentials: password database acquired from // realmName: current realm the object name object Principal = username; // object Credentials = "123456"; object Credentials = new new SimpleHash ( "the MD5", "123456", "",. 1 ); String realmName = the this .getName (); SimpleAuthenticationInfo info = new new SimpleAuthenticationInfo (principal, credentials, realmName) ;return info; } / ** * authorization rights information, including roles and privileges * / @Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) { System.out.println ( "rights profile -> MyShiroRealm.doGetAuthorizationInfo ()" ); SimpleAuthorizationInfo authorizationInfo = new new SimpleAuthorizationInfo (); // if authentication is not passed when the User object, here only to take userName // is SimpleAuthenticationInfo structure when the first argument needs to User objects String userName = (String) principalCollection.getPrimaryPrincipal ( ); // according username query roles and permissions information from the database is not mentioned here //构造角色数据 if(userName.equals("zhangsan")){ authorizationInfo.addRole("role1"); authorizationInfo.addRole("role2"); } if(userName.equals("lisi")){ authorizationInfo.addRole("role1"); } //构造权限数据 if(userName.equals("zhangsan")){ authorizationInfo.addStringPermission("user:list"); authorizationInfo.addStringPermission("user:add"); authorizationInfo.addStringPermission("user:delete"); } if(userName.equals("lisi")){ authorizationInfo.addStringPermission("user:list"); } return authorizationInfo; } public static void main(String[] args) { String algorithmName="MD5"; String source="123456"; String salt=""; int hashIterations=1; Object result=new SimpleHash(algorithmName, source, salt, hashIterations); System.out.println(result); } }
ShiroTestController url to access the test after simulated landing
import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.UnauthorizedException; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.subject.Subject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("") public class ShiroTestController { @RequestMapping(value = "/dologin") public String login() { System.out.println("------登录-------"); String msg = ""; //String username = "zhangsan"; String username = "lisi"; String password = "123456"; UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); if (subject.isAuthenticated ()) { return"login success" ; } the else { return "Login Failed" ; } } the catch (IncorrectCredentialsException E) { MSG =. "Wrong password for Account Password" token.getPrincipal + () + "WAS here Incorrect." ; The System.out. the println (MSG); } the catch (ExcessiveAttemptsException E) { MSG = "too many failed login" ; System.out.println (MSG); } the catch (LockedAccountException E) { MSG = "account is locked the account for username." + token.getPrincipal () + "WAS Locked." ; System.out.println(msg); } catch (DisabledAccountException e) { msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled."; System.out.println(msg); } catch (ExpiredCredentialsException e) { msg = "帐号已过期. the account for username " + token.getPrincipal() + " was expired."; System.out.println(msg); } catch (UnknownAccountException e) { msg = "Account does not exist with username User NO IS There of." + Token.getPrincipal (); System.out.println (MSG); } the catch (UnauthorizedException E) { MSG = "! You do not have authorization to give the corresponding" + E .getMessage (); System.out.println (MSG); } return "Login" ; } @RequestMapping (value = "Zimbabwe Logout", Method = RequestMethod.GET) public String Zimbabwe Logout () { System.out.println ( "- ----- quit ------- " ); Subject Subject = SecurityUtils.getSubject (); IF (Subject!= null ) { the try { subject.logout (); } the catch (Exception ex){ } } return "to exit the success" ; } @ RequestMapping ( "/ index" ) public String index () { System.out.println ( "enter Home ------ ------- " ); return " into the home " ; } @RequestMapping ( " / unauthorized " ) public String unauthorized () { System.out.println ( " unauthorized ------ ---- --- " ); return " not authorized " ; } @ RequestMapping ( "/ userList" ) @RequiresPermissions ( "the User:list") public String userList () { System.out.println ( "User List ------ -------" ); return "User List" ; } @RequestMapping ( "/ The userAdd" ) @RequiresPermissions ( " user: the Add " ) public String The userAdd () { System.out.println ( " Add user ------ ------- " ); return " Add user " ; } @RequestMapping ( " / userDelete " ) @RequiresPermissions("User: Delete" ) public String userDelete () { System.out.println ( "Delete User ------ -------" ); return "user deletes" ; } }