1. Spring Boot Integrated Shiro Basic Configuration
Introduce dependencies:
In Spring Boot ProjectAdd Shiro-related dependencies to (if it is a Maven project), for example:
<dependency> <groupId></groupId> <artifactId>shiro-spring-boot-starter</artifactId> <version>1.7.1</version> </dependency>
The version number here can be adjusted according to actual needs.
Create a Shiro configuration class:
Create a configuration class, for exampleShiroConfig
, used to configure the core components of Shiro, such as Security Manager, FilterChain, etc.
import ; import ; import ; import ; import ; import ; import ; import ; @Configuration @ImportAutoConfiguration({, }) public class ShiroConfig { @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean() { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // Set up the security manager, create and inject it later (securityManager()); // Configure filter chain Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); ("/login", "anon"); ("/**", "authc"); (filterChainDefinitionMap); return shiroFilterFactoryBean; } @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // Set Realm, create and inject it later (userRealm()); return securityManager; } @Bean public UserRealm userRealm() { return new UserRealm(); } }
In the above configuration, which URLs are defined to be authenticated (authc
), which ones can be accessed anonymously (anon
) and set up the Security Manager and related Realm (components for user authentication and authorization).
2. User authentication and authorization implementation (Shiro-based Realm)
Create Realm class:
Create an inherited fromAuthorizingRealm
Classes, such asUserRealm
, used to implement user authentication and authorization logic.
import ; import ; import ; import ; import ; import ; import ; import ; public class UserRealm extends AuthorizingRealm { @Override protected AuthenticationInfo doAuthentication(AuthenticationToken token) throws AuthenticationException { // Get information such as username and password. Here it is assumed to get it from the token String username = (String) (); String password = new String((char[]) ()); // In actual applications, user information should be queried from databases and other places for verification User user = (username); if (user == null) { throw new AuthenticationException("The user does not exist"); } if (!().equals(password)) { throw new AuthenticationException("Error password"); } // Pass the authentication and return the authentication information return new SimpleAuthenticationInfo(user, (), getName()); } @Override protected AuthorizationInfo doAuthorization(AuthorizationInfo authorizationInfo) { // Get the current user User user = (User) getSubject().getPrincipal(); // Set authorization information based on user role and permission information SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); List<Role> roles = (); for (Role role : roles) { (()); List<Permission> permissions = (); for (Permission permission : permissions) { (()); } } return simpleAuthorizationInfo; } }
existdoAuthentication
The user authentication logic is implemented in the method, and the user's user name and password are verified by querying the database, etc. existdoAuthorization
In the method, authorization information is set according to the user's role and permission information.
3. Permission refresh mechanism
1. Permission refresh based on cache cleaning
When permissions change (such as the administrator modifying the user's role or permissions in the background), you can refresh the permissions by cleaning up Shiro-related caches.
Add cache management in Realm:
existUserRealm
In the class, the cache mechanism provided by Shiro can be used to cache user authentication and authorization information to improve performance. For example:
import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; @Configuration @ImportAutoConfiguration({, }) public class ShiroConfig { @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean() { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // Set up the security manager, create and inject it later (securityManager()); // Configure filter chain Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); ("/login", "anon"); ("/**", "authc"); (filterChainDefinitionMap); return shiroFilterFactoryBean; } @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // Set Realm, create and inject it later (userRealm()); return securityManager; } @Bean public UserRealm userRealm() { UserRealm userRealm = new UserRealm(); // Set up the cache manager (cacheManager()); return userRealm; } @Bean public CacheManager cacheManager() { // Here you can select different cache managers to implement according to the actual situation, such as Ehcache, Redis, etc. return new MemoryCacheManager(); } }
Set hereMemoryCacheManager
As a cache manager example, in actual applications, more suitable ones can be selected according to the needs, such asRedisCacheManager
wait.
Clean up cache when permissions are modified:
When permissions change, the corresponding cache needs to be cleaned in the relevant business logic code (such as in the service method that modify user roles or permissions). For example:
import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; @Configuration @ImportAutoConfiguration({, }) public class ShiroConfig { @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean() { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // Set up the security manager, create and inject it later (securityManager()); // Configure filter chain Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); ("/login", "anon"); ("/**", "authc"); (filterChainDefinitionMap); return shiroFilterFactoryBean; } @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // Set Realm, create and inject it later (userRealm()); return securityManager; } @Bean public UserRealm userRealm() { UserRealm userRealm = new UserRealm(); // Set up the cache manager (cacheManager()); return userRealm; } @Bean public CacheManager cacheManager() { // Here you can select different cache managers to implement according to the actual situation, such as Ehcache, Redis, etc. return new MemoryCacheManager(); } // In the service method of permission modification public void updateUserPermissions(User user, List<Permission> newPermissions) { // Update the user permission information in the database first (user, newPermissions); // Clean up the cache Cache<String, AuthorizationInfo> cache = userRealm().getCacheManager().getCache("authorizationCache"); if (cache!= null) { (); } } }
In this way, when calledupdateUserPermissions
After modifying user permissions, the cache of authorization information will be cleaned up. The next time the user accesses the relevant resources, Shiro will re-authorize the authorization calculation.
2. Actively trigger authorization updates
In addition to indirectly realizing permission refresh by cleaning the cache, authorization updates can also be actively triggered when permissions change.
Add update authorization method in Realm:
existUserRealm
Add a method to the class to trigger authorization updates manually, for example:
import ; import ; import ; import ; import ; import ; import ; import ; public class UserRealm extends AuthorizingRealm { //... The previous authentication and authorization methods public void updateAuthorization(User user) { PrincipalCollection principals = getSubject().getPrincipals(); if (principals!= null && (user)) { (principals); } } }
This method obtains the main information of the current user and then callsto re-perform authorization calculation.
Call the update authorization method in the permission modification business logic:
In modifying user permissions and other related business logic codes, call the aboveupdateAuthorization
Method to proactively trigger authorization updates. For example:
import ; import ; import ; import ; import ; import ; import ; import ; public class UserService { //... Other business methods public void updateUserPermissions(User user, List<Permission> newPermissions) { // Update the user permission information in the database first (user, newPermissions); // Actively trigger authorization update UserRealm userRealm = (UserRealm) ("userRealm"); (user); } }
In this way, when permissions change, the user's authorization information can be updated promptly and proactively to ensure that the user's permission access complies with the latest settings.
To sum up, when Spring Boot is managed in combination with Shiro, by reasonably configuring Shiro's basic components and implementing an effective permission refresh mechanism, the security of the system and the flexibility of permission management can be better guaranteed.
This is the article about springBoot integrated shiro to implement permission refresh. For more relevant springBoot shiro permission refresh content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!