In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to use spring-shiro permissions to control realm". In daily operation, I believe many people have doubts about how to use spring-shiro permissions to control realm. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to use spring-shiro permissions to control realm". Next, please follow the editor to study!
Catalogue
Spring-shiro privilege Control realm
User and role entity
Realm class
Shiro configuration class
Controller
Service
Analysis of the reasons for the ineffectiveness of shiro permissions
The pit encountered by shiro
Cause of problem: permission label definition problem
Spring-shiro permissions control realm users and role entities
Role.java
@ Data@Entitypublic class Role {@ Id @ GeneratedValue private Integer id; private Long userId; private String role;}
User.java
@ Data@Entitypublic class User {@ Id @ GeneratedValue private Long id; private String username; private String password;} Realm class
First set up the Realm class, which inherits from AuthorizingRealm, and customize our own authorization and authentication methods. Realm is a component that can access application-specific security data, such as users, roles, and permissions.
Realm.java
Public class Realm extends AuthorizingRealm {@ Autowired private UserService userService; / / Authorization @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {/ / obtain the user name from the credential String username = (String) SecurityUtils.getSubject () .getPrincipal (); / / query the user object User user = userService.getUserByUserName (username) based on the user name / / query the roles owned by the user List list = roleService.findByUserId (user.getId ()); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo (); for (Role role: list) {/ / assign the user the role info.addStringPermission (role.getRole ());} return info } / / authenticate @ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authenticationToken) throws AuthenticationException {/ / get the user name of the current user String username = (String) authenticationToken.getPrincipal (); / / find the user User user = userService.getUserByUserName (username) based on the user name from the database If (userService.getUserByUserName (username) = = null) {throw new UnknownAccountException ("No corresponding user information was found in this system.") ;} SimpleAuthenticationInfo info = new SimpleAuthenticationInfo (user.getUsername (), user.getPassword (), getName ()); return info;}} Shiro configuration class
ShiroConfig.java
@ Configurationpublic class ShiroConfig {@ Bean public ShiroFilterFactoryBean shiroFilterFactoryBean (SecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean (); shiroFilterFactoryBean.setSecurityManager (securityManager); Map filterChainDefinitionMap = new LinkedHashMap (); / / the following is the filter chain, which is filtered sequentially, so / * * you need to put the last / / open static resource filterChainDefinitionMap.put ("/ favicon.ico", "anon") / / website icon filterChainDefinitionMap.put ("/ * *", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap (filterChainDefinitionMap); return shiroFilterFactoryBean;} @ Bean public DefaultWebSecurityManager securityManager () {DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager (myRealm ()); return defaultWebSecurityManager;} @ Bean public MyRealm myRealm () {MyRealm myRealm = new MyRealm (); return myRealm;}} Controller
UserController.java
Controllerpublic class UserController {@ Autowired private UserService userService; @ GetMapping ("/") public String index () {return "index";} @ GetMapping ("/ login") public String toLogin () {return "login";} @ GetMapping ("/ admin") public String admin () {return "admin" } @ PostMapping ("/ login") public String doLogin (String username, String password) {UsernamePasswordToken token = new UsernamePasswordToken (username, password); Subject subject = SecurityUtils.getSubject (); try {subject.login (token);} catch (Exception e) {e.printStackTrace ();} return "redirect:admin" } @ GetMapping ("/ home") public String home () {Subject subject = SecurityUtils.getSubject (); try {subject.checkPermission ("admin");} catch (UnauthorizedException exception) {System.out.println ("not enough permissions");} return "home" } @ GetMapping ("/ logout") public String logout () {return "index";}} Service
UserService.java
@ Servicepublic class UserService {@ Autowired private UserDao userDao; public User getUserByUserName (String username) {return userDao.findByUsername (username);} @ RequiresRoles ("admin") public void send () {System.out.println ("I now have the role admin, I can execute this statement");}} the reason why the shiro permission does not take effect analyze the hole encountered by shiro
-shiro is used for login verification and permission management in the project. If you encounter a pit when configuring permissions, record it.
Environment: springboot+freemarker+shiro
Scenario: background management, configuration menu and button permissions are divided into three levels, level 1 and level 2 only consider whether to view permissions, and level 3 is page button permissions, which are added, deleted, modified and checked. See the picture for details.
Problem: the first and second levels are normal, and the third level permissions do not work!
The permission label is defined as follows:
Tag definition page one page two first level one:viewtwo:view second level one:page1:viewtwo:page2:view third level one:page1:view:addtwo:page2:view:add
At first, it was suspected that the database was not entered. After checking, the permission label has been corresponding to the role and excluded.
Later suspected is the page problem, after the third-level label and the first and second level of the same page, still does not work, excluded.
It is suspected that the definition of the permission label is the problem. Change the third-level tag to one:page1:data:add, a miracle occurs, and the permission takes effect. Confirm that there is something wrong with the permission label definition.
Cause of problem: permission label definition problem
But then I thought about why this problem occurred. Each tag was unique. I was interested in shiro's verification of permission tags, looked at the source code, and finally saw the key point in org.apache.shiro.authz.permission after debug. The core code is as follows
/ / indicates that this permission exists when this method returns true / / this p represents the permission label public boolean implies (Permission p) {/ / By default only supports comparisons with other WildcardPermissionsif (! (p instanceof WildcardPermission)) {return false;} WildcardPermission wp = (WildcardPermission) p matched by the current loop. / / split the current tag into a set collection (for example, one:page1:view:add will be divided into [[one], [page1], [view], [add]]) List otherParts = wp.getParts (); int I = 0 / / cyclic matching permission tags for (Set otherPart: otherParts) {/ / If this permission has less parts than the other permission, everything after the number of parts contained / / in this permission is automatically implied, so return true / / when no false is returned after all the loops are matched, true is returned. The getparts () method is to get the permission tags of the current loop of the current role ([[one], [page1]). [view]]) if (getParts () .size ()-1 < I) {return true } else {Set part = getParts () .get (I) / * return false if it contains'* 'and does not contain the currently split tag, * when the user can view the page That is to say, the current character has an one:page1:view tag * here [! part.contains (WILDCARD_TOKEN)] returns true, and the second [part.containsAll (otherPart)] one matches the current tag * * with one, * that is, all the false is returned after the loop, so there is no true in the end, so a true is returned on it. If (! part.contains (WILDCARD_TOKEN) & &! part.containsAll (otherPart)) {return false;} iTunes;}}
Summary: through the analysis, we see that when defining permission tags in shiro, we should pay attention to the matching problem, and there should be no inclusion problems, such as aaa and aaab, which will lead to the invalidation of later tags.
At this point, the study on "how to use spring-shiro permissions to control realm" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.