SpringBoot integrates Shiro for permission Control and Management. springbootshiro
Shiro
Apache shiro is a lightweight authentication and authorization framework. Compared with spring security, it is easy to use and flexible. springboot itself provides security support. After all, it is its own thing. Springboot is not integrated with shiro at the moment, so you have to configure it yourself.
1. Add dependency
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.5</version> </dependency>
2. Compile the Shiro configuration class
Package com. xbz. web. system. config; import. pollux. thymeleaf. shiro. dialect. shiroDialect; import org. apache. shiro. authc. credential. credentialsMatcher; import org. apache. shiro. authc. credential. hashedCredentialsMatcher; import org. apache. shiro. cache. ehcache. ehCacheManager; import org. apache. shiro. codec. base64; import org. apache. shiro. session. sessionListener; import org. apache. shiro. session. mgt. sessio NManager; import org. apache. shiro. session. mgt. eis. memorySessionDAO; import org. apache. shiro. session. mgt. eis. sessionDAO; 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. cookieRememberMeManager; import org. apach E. shiro. web. mgt. defaultWebSecurityManager; import org. apache. shiro. web. servlet. simpleCookie; import org. apache. shiro. web. session. mgt. defaultWebSessionManager; import org. springframework. aop. framework. autoproxy. defaultAdvisorAutoProxyCreator; import org. springframework. boot. autoconfigure. condition. conditionalOnMissingBean; import org. springframework. context. annotation. bean; import org. springframewo Rk. context. annotation. configuration; import org. springframework. context. annotation. dependsOn; import java. util. arrayList; import java. util. collection; import java. util. linkedHashMap; import java. util. map;/*** shiro configuration class * ApacheShiro core uses Filter to implement permission control and interception, just as SpringMVC uses DispachServlet to control request distribution. * Since Filter is used, URL rules are used for filtering and permission verification, we need to define a series of URL rules and access permissions */@ Configuration public class ShiroConf Iguration {/*** DefaultAdvisorAutoProxyCreator, a bean of Spring, which is determined by Advisor to implement AOP proxy for the methods of which classes. * // @ Bean @ ConditionalOnMissingBean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator () {defaadadvisorautoproxycreator defaultAAP = new DefaultAdvisorAutoProxyCreator (); defaultAAP. setProxyTargetClass (true); return defaultAAP;}/*** ShiroFilterFactoryBean: Process intercepted resource files to generate ShiroFilter Problem. * It mainly maintains three types of data: securityManager, filters, and filterChainDefinitionManager. * Note: The configuration of a single ShiroFilterFactoryBean is incorrect, because injection is required when ShiroFilterFactoryBean is initialized: SecurityManager ** FilterChain definition Description * 1. multiple filters can be configured for a URL, separated by commas (,) * 2. when multiple filters are set, all the filters pass the verification and are considered to pass * 3. some filters can specify parameters, such as perms, roles **/@ Bean public ShiroFilterFactoryBean shiroFilterFactoryBean () {ShiroFilterFactoryBean shiroFilterFact OryBean = new ShiroFilterFactoryBean (); shiroFilterFactoryBean. setSecurityManager (securityManager (); shiroFilterFactoryBean. setLoginUrl ("/login"); // if this parameter is not set, login under the root directory of the web project is located by default. jsp page shiroFilterFactoryBean. setSuccessUrl ("/index"); // The Connection shiroFilterFactoryBean to be redirected after successful logon. setUnauthorizedUrl ("/403"); // unauthorized jump page/* // custom interceptor, multiple filter settings * // Map <String, filter> filters = new LinkedHashMap <> (); // LogoutFilter LogoutFilter = new LogoutFilter (); // limit the number of concurrent online requests of the same account. Or Single Sign-On. // logoutFilter. setRedirectUrl ("/login"); // filters. put ("logout", null); // shiroFilterFactoryBean. setFilters (filters); Map <String, String> filterChainDefinitionMap = new LinkedHashMap <> (); // filterChainDefinitionManager must be a LinkedHashMap because it must ensure an ordered filterChainDefinitionMap. put ("/css/**", "anon"); // permission is not required for static resources. If there are files in other directories (such as js and img) set filterChainDefinitionMap accordingly. put ("/", "anon"); filterChainDefinitionMap. put ("/login", "anon"); // configure some URLs filterChainDefinitionMap that do not require permission access. put ("/logout", "logout"); filterChainDefinitionMap. put ("/user/**", "authc, roles [ROLE_USER]"); // The role ROLE_USER can be accessed. the User Role controls user behavior. filterChainDefinitionMap. put ("/events/**", "authc, roles [ROLE_ADMIN]"); // filterChainDefinitionMap. put ("/user/edit/**", "authc, perms [user: edit]"); // for the purpose of testing, fixed write dead value, it can also be read from the database or other configurations, where filterChainDefinitionMap is controlled with permissions. put ("/**", "authc"); // The resource to be accessed, usually put/** at the bottom of shiroFilterFactoryBean. setFilterChainDefinitionMap (filterChainDefinitionMap); return shiroFilterFactoryBean ;} // region Cookie and Session ================================ Cookie and Session management begin ======== ============== private static final String COOKIE_NAME = "rememberMe "; /** cookie Object Management */public SimpleCookie rememberMeCookie () {// this parameter is the cookie name, corresponding to the front-end checkbox name = rememberMe SimpleCookie simpleCookie = new SimpleCookie (COOKIE_NAME ); simpleCookie. setMaxAge (604800); // remember me the effective time of the cookie is 7 days, the unit is return simpleCookie;}/** cookie management object: Remember Me function */public CookieRememberMeManager rememberMeManager () {CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager (); cookieRememberMeManager. setCookie (rememberMeCookie (); cookieRememberMeManager. setCipherKey (Base64.decode ("3AvVhmFLUs0KTA3Kprsdag ="); // The rememberMe cookie-Encrypted Key is recommended for each project. The default AES algorithm key length (128 256 bits) is different from that for each project ;} @ Bean SessionDAO sessionDAO () {return new MemorySessionDAO ();} @ Bean public SessionManager sessionManager () {defawebwebsessionmanager sessionManager = new defawebwebsessionmanager (); collection <SessionListener> listeners = new ArrayList <> (); listeners. add (new BDSessionListener (); sessionManager. setSessionListeners (listeners); sessionManager. setSessionDAO (sessionDAO (); return sessionManager ;} // ================================ Cookie and Session management end ==================== ========/// endregion/*** SecurityManager: core Security Transaction Manager, permission management * this class combines login, logout, permission, and session processing. is an important class. */@ Bean (name = "securityManager") public DefaultWebSecurityManager securityManager () {defawebwebsecuritymanager securityManager = new DefaultWebSecurityManager (); securityManager. setRealm (shiroRealm (); securityManager. setCacheManager (ehCacheManager (); // user authorization/authentication information Cache, using EhCache Cache // custom session management using redis securityManager. setSessionManager (sessionManager (); // inject my account manager; securityManager. setRememberMeManager (rememberMeManager (); return securityManager;}/*** ShiroRealm, a custom authentication class that inherits from AuthorizingRealm and * processes user authentication and permissions, see the implementation of JdbcRealm. * // @ Bean @ DependsOn ("lifecycleBeanPostProcessor") public ShiroRealm shiroRealm (CredentialsMatcher matcher) {ShiroRealm realm = new ShiroRealm (); realm. setCredentialsMatcher (matcher); // return realm for password verification;}/*** EhCacheManager. After a user logs on to the Cache Management Console, the user information and permission information are cached, then, each user request is placed in the user's session. If this bean is not set, each request will query the database once. */@ Bean @ DependsOn ("lifecycleBeanPostProcessor") public EhCacheManager ehCacheManager () {EhCacheManager em = new EhCacheManager (); em. setCacheManagerConfigFile ("classpath: config/ehcache. xml "); // configuration file path return em;}/*** LifecycleBeanPostProcessor, which is a subclass of DestructionAwareBeanPostProcessor and * is responsible for org. apache. shiro. util. initialize and destroy the lifecycle of the Initializable bean. * It is mainly a subclass of the AuthorizingRealm class and the EhCacheManager class. */@ Bean (name = "canonical") public lifecycleBeanPostProcessor LifecycleBeanPostProcessor () {return new lifecycleBeanPostProcessor () ;}/ *** encode, this class is used to encode the password, * prevent the password from being explicitly stored in the database. Of course, during login authentication, * this class is also responsible for encoding the password entered in the form * processing the authentication matching processor: if you need to implement custom inheritance HashedCredentialsMatcher */@ Bean (name = "secret") public writable entity () {hashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher. setHashAlgorithmName ("MD5"); // specifies the encryption method. You can also add the cache here. If the user fails to log on more than five times, the user will be locked and cannot log on to credentialsMatcher. setHashIterations (2); credentialsMatcher. setStoredCredentialsHexEncoded (true); return credentialsMatcher;}/*** AuthorizationAttributeSourceAdvisor, Advisor class implemented in shiro, * internal use of token to intercept methods with the following annotations. */@ Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor () {AuthorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor (); advisor. setSecurityManager (securityManager (); return advisor;} // when integrating the thymeleaf template engine and shiro, use @ Bean public ShiroDialect shiroDialect () {return new ShiroDialect ();}}
3. Custom Realm verification class
Package com. yiyun. web. system. config; import com. yiyun. dao. master. userDao; import com. yiyun. domain. userDO; import com. yiyun. web. common. utils. shiroUtils; import com. yiyun. web. system. service. menuService; import org. apache. shiro. securityUtils; import org. apache. shiro. authc. *; import org. apache. shiro. authz. authorizationInfo; import org. apache. shiro. authz. simpleAuthorizationInfo; import org. apache. shiro. Realm. authorizingRealm; import org. apache. shiro. session. session; import org. apache. shiro. subject. principalCollection; import org. springframework. beans. factory. annotation. autowired; import java. util. *;/*** get user role and permission information */public class ShiroRealm extends AuthorizingRealm {// generally, servic @ Autowired private UserDao userMapper is written here; @ Autowired private MenuService menuService;/*** generally, after successful logon The current user is granted permissions * authorization judgment based on the user's permission information. This step is based on doGetAuthenticationInfo, only after the user information is available can the user determine whether to authorize the user based on the user's role and authorization information, therefore, here the Roles and Permissions are the two key judgment bases of users * @ param authenticationToken * @ return * @ throws AuthenticationException */@ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authenticationToken) throws AuthenticationException {UsernamePasswordToken token = (UsernamePasswordToken) AuthenticationToken; UserDo user = userMapper. findByName (token. getUsername (); // check whether the user if (user! = Null) {// if the user exists, store the user in the logon authentication info. You do not need to compare the passwords yourself, shiro will compare and verify the password List <URole> rlist = uRoleDao. findRoleByUid (user. getId (); // obtain the User Role List <UPermission> plist = uPermissionDao. findPermissionByUid (user. getId (); // obtain the user permission List <String> roleStrlist = new ArrayList <String> (); //// List of user role sets <String> perminsStrlist = new ArrayList <String> (); // set of user permissions for (URole role: rlist) {roleStrlist. add (role. getName ();} (UPermission uPermission: plist) {perminsStrlist. add (uPermission. getName ();} user. setRoleStrlist (roleStrlist); user. setPerminsStrlist (perminsStrlist); Session session = SecurityUtils. getSubject (). getSession (); session. setAttribute ("user", user); // If the authentication succeeds, the user is put into the session. // If the authentication succeeds, the user is stored in the logon authentication info without comparing the password, shiro will perform password verification return new SimpleAuthenticationInfo (user, user. getPassword (), getName ();} return nu Ll;}/** permission authentication * to obtain the user's permission information, which is used to determine the next authorization, obtain the role information of the current user and the permissions of these roles * @ param principalCollection * @ return */@ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {// obtain the username entered by the current logon. It is equivalent to (String) principalCollection. fromRealm (getName ()). iterator (). next (); // String loginName = (String) super. getAvailablePrincipal (principalCollection); UserDo user = (UserDo) PrincipalCollection. getPrimaryPrincipal (); // check whether this object exists in the Database // User user = null; // in the actual project, cache can be performed based on the actual situation. If not, shiro also has a time interval mechanism. This method will not be executed repeatedly within 2 minutes. // user = userMapper. findByName (loginName); if (user! = Null) {// permission information object info, used to store all roles and permission of the user to be identified SimpleAuthorizationInfo = new SimpleAuthorizationInfo (); // user role set info. addRoles (user. getRoleStrlist (); // set of User Permissions info. addStringPermissions (user. getPerminsStrlist (); return info;} // If null is returned, any user's access to intercepted requests will automatically jump to the address specified by unauthorizedUrl and return null ;}}
4. Check the ehcache configuration file.
<? Xml version = "1.0" encoding = "UTF-8"?> <Ehcache xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: noNamespaceSchemaLocation = "http://ehcache.org/ehcache.xsd" updateCheck = "false"> <diskStore path = "java. io. tmpdir/Tmp_EhCache"/> <! -- Name: cache name. MaxElementsInMemory: Maximum number of caches maxElementsOnDisk: Maximum number of Hard Disk caches. Eternal: whether the object is permanently valid. Once set, timeout does not work. OverflowToDisk: whether to save to the disk. When the system is running, timeToIdleSeconds: sets the allowed idle time (unit: seconds) before the object expires ). This attribute is optional only when the eternal = false object is not permanently valid. The default value is 0, indicating that the idle time is infinite. TimeToLiveSeconds: sets the allowed lifetime of an object before it expires (unit: seconds ). The maximum time is between the creation time and the expiration time. It is used only when the eternal = false object is not permanently valid. The default value is 0. That is, the object survival time is infinite. DiskPersistent: Whether to cache data during VM restart Whether the disk store persists between restarts of the Virtual Machine. the default value is false. diskSpoolBufferSizeMB: this parameter sets the cache size of DiskStore (disk cache. The default value is 30 MB. Each Cache should have its own buffer. DiskExpiryThreadIntervalSeconds: Specifies the interval for running a disk failure thread. The default value is 120 seconds. MemoryStoreEvictionPolicy: When the maxElementsInMemory limit is reached, Ehcache clears the memory according to the specified policy. The default policy is LRU (least recently used ). You can set it to FIFO (first-in-first-out) or LFU (rarely used ). ClearOnFlush: whether to clear when the maximum number of memory is exceeded. MemoryStoreEvictionPolicy: Three clearing policies of Ehcache; FIFO, first in first out, which is the most familiar and advanced. LFU and Less Frequently Used are the strategies Used in the above example. To put it bluntly, they are least Used. As mentioned above, the cached element has an hit attribute, and the minimum hit value will be cleared out of the cache. LRU, Least Recently Used, Least Recently Used. The cached element has a timestamp. When the cache capacity is full and you need to make room for caching new elements, the elements whose timestamp is the farthest from the current time in the existing cache will be cleared out of the cache. --> <DefaultCache eternal = "false" maxElementsInMemory = "1000" overflowToDisk = "false" diskPersistent = "false" timeToIdleSeconds = "0" timeToLiveSeconds = "600" longitude = "LRU "/> <! -- Logon record cache locked for 10 minutes --> <cache name = "passwordRetryCache" maxEntriesLocalHeap = "2000" eternal = "false" timeToIdleSeconds = "3600" timeToLiveSeconds = "0" overflowToDisk = "false "statistics =" true "> </cache> </ehcache>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.