In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to use the Apache shiro framework, the article is very detailed, has a certain reference value, interested friends must read it!
Brief introduction of apache shiro Framework
Apache Shiro is a powerful and flexible open source security framework that neatly handles authentication, authorization, enterprise session management and encryption. Nowadays, more and more people are using Apache Shiro, because it is quite simple and may not have as many powerful functions as Spring Security compared to Spring Security,Shiro, but it may not require so complex things in practice, so a simple Shiro is sufficient.
Here are some things you can do with Apache Shiro:
Four core parts of Shiro-authentication, authorization, session management and encryption
Authentication: authentication, or "login" for short.
Authorization: authorization, assigning roles or permission resources to users
Session Management: user session manager, which allows CS programs to also use session to control permissions
Cryptography: encapsulate the complex password encryption methods in JDK.
In addition to the above features, shiro also provides a number of extensions
Web Support: provides some common functions mainly for web applications.
Caching: caching can make applications run more efficiently.
Concurrency: multithreading related functions.
Testing: help us test related functions
Run As: a feature that allows a user to assume the identity of another user (if allowed) is sometimes useful in administrative scripts.
Remember Me: remember the user's identity and provide a shopping cart-like function.
Shiro framework authentication process
Application Code: application code, developed by developers
Subject: the interface provided by the framework is the object that interacts with the program, which can be a person, a service or something else, usually understood as a user. All Subject instances must be bound to a SecurityManager. We interact with a Subject, and the runtime shiro is automatically translated into a specific subject interaction with the SecurityManager.
SecurityManager: the interface provided by the framework, which is the core of Shiro and represents the security manager object. Coordinate the operation of each module during initialization. However, once the SecurityManager is coordinated, the SecurityManager will be left alone, and we only need to operate the Subject, not the SecurityManager. But we need to know that when we are interacting with a Subject, it is essentially the SecurityManager that handles Subject security operations.
Realm: can be written by developers, and the framework also provides some. Realms acts as a "bridge" or "connector" between applications and security data in Shiro. He obtains security data to determine whether subject can log in and what permissions subject has. He is a bit like DAO. At least one realm is required when configuring realms. And Shiro provides some common Realms to connect to the data source, such as the JndiLdapRealm,JDBC data source of the LDAP data source, the JdbcRealm,ini file of the IniRealm,properties file data source, the PropertiesRealm of the IniRealm,properties file data source, and so on. We can also insert our own Realm implementation to represent custom data sources. Like other components, Realms is controlled by SecurityManager.
A more detailed picture
Let's start the integrated use of shiro and SSM project.
Download address: http://shiro.apache.org/download.html
Download these two files, a jar package and a source file
First, the first step is to import the jar package into the project
Then, the second step is to configure the filter provided by the spring framework to integrate the shiro framework in web.xml (be sure to put it in front of the springmvc or struts framework filter, just put it on top just to be on the safe side)
ShiroFilter org.springframework.web.filter.DelegatingFilterProxy shiroFilter / *
Third, configure bean,id as shiroFilter in the spring configuration file
/ script/** = anon / style/** = anon / index.jsp* = anon / noPrivilegeUI.jsp* = anon / user/login = anon / role/findAllRoleList = perms [role Management] / * = authc
SecurityManager: this attribute is required.
LoginUrl: users who do not log in automatically jump to the login page when they request a login page, which is not a required attribute. If you do not enter the address, you will automatically find the "/ login.jsp" page under the root directory of the project web project.
SuccessUrl: log in successfully and jump to the default page, which can be redirected to "/" if it is not configured. If you click on a page you need to log in before logging in, you will automatically jump to the page where you need to log in when you log in. No, jump here.
UnauthorizedUrl: a page that does not have permission to jump to by default.
Anon: example / admins/** = anon has no parameters, which means it can be used anonymously (authentication (login) required).
Authc: for example, / admins/user/** = authc means authentication (login) is required to use it. There are no parameters.
Roles: example / admins/user/** = roles [admin]. Multiple parameters can be written in quotation marks, and the parameters are separated by commas. When there are multiple parameters, such as admins/user/** = roles ["admin,guest"], each parameter is passed, which is equivalent to the hasAllRoles () method.
Perms: example / admins/user/** = perms [user:add:*], multiple parameters can be written in quotation marks, and the parameters are separated by commas, for example, / admins/user/** = perms ["user:add:*,user:modify:*"]. When there are multiple parameters, each parameter must be passed before it can be passed, if you want to use the isPermitedAll () method.
Rest: example / admins/user/** = rest [user]; according to the requested method, it is equivalent to / admins/user/** = perms [user:method]; where method is post,get,delete and so on.
Port: example / admins/user/** = port [8081]; when the port of the requested url is not 8081, it jumps to schemal://serverName:8081?queryString, where schmal is the protocol http or https, etc. ServerName is the port of port in the url configuration that you access, queryString
Is it from the url you visited? The following parameters.
AuthcBasic: for example, / admins/user/** = authcBasic;. No parameter indicates httpBasic authentication.
Ssl: example / admins/user/** = ssl; has no parameters, indicating a secure url request. The protocol is https.
User: for example, / admins/user/** = user;. No parameter indicates that there must be a user, and no check is made when logging in.
Note: anon,authcBasic,auchc,user is the authentication filter
Perms,roles,ssl,rest,port is the authorization filter
Step 4: configure the security manager
Step 5: write a login method to perform the authentication operation using the method provided by shiro
This is my previous login method. In this way, shiro does not know that the login authentication has passed and has not been passed, so we have to log in in the way of authentication provided by shiro.
/ * Log in * / @ RequestMapping ("/ login") public String login (User user, HttpServletRequest request, Model model) {HttpSession session = request.getSession (); User newUser = userService.login (user); if (newUser! = null) {session.setAttribute ("loginUser", newUser); return "home/home";} model.addAttribute ("errorMessage", "user name or password is incorrect!") ; return "forward:/index.jsp";}
Modified login method
/ * * login authentication using the method provided by the Shiro framework * / @ RequestMapping ("/ login") public String login (User user, HttpServletRequest request, Model model) {HttpSession session = request.getSession (); / / use the method provided by the Shiro framework to authenticate Subject subject = SecurityUtils.getSubject () / / get the current login user object, and the current status is "unauthenticated" / / username password token AuthenticationToken token = new UsernamePasswordToken (user.getLoginName (), MD5Utils.md5 (user.getPassword (); try {subject.login (token); / / execute your custom Realm User user1 = (User) subject.getPrincipal (); session.setAttribute ("loginUser", user1); return "home/home" } catch (UnknownAccountException e) {e.printStackTrace (); model.addAttribute ("errorMessage", "this username does not exist!") ;} catch (IncorrectCredentialsException e) {e.printStackTrace (); model.addAttribute ("errorMessage", "password is incorrect!") ;} catch (Exception e) {e.printStackTrace ();} return "forward:/index.jsp";}
Step 6: customize realm and inject it into the security manager
Create a UserRealm class that inherits the AuthorizingRealm class
Public class UserRealm extends AuthorizingRealm {@ Autowired private UserDao userDao; / / authentication method @ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {System.out.println ("the authentication method in realm has been executed.") ; UsernamePasswordToken myToken = (UsernamePasswordToken) token; String loginName = myToken.getUsername (); / / query the user in the database according to the user name. This method is written by yourself, User user = userDao.findUserByLoginName (loginName); if (user = = null) {/ / user name does not exist return null } / / if it can be queried, the framework compares whether the password queried in the database is consistent with the password submitted on the page AuthenticationInfo info = new SimpleAuthenticationInfo (user, user.getPassword (), this.getName ()); return info;} / / Authorization method @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) {return null;}}
Inject custom realm into the security manager
The program can run normally here. Log in and go to the home page.
However, if you click on role Management, you will go to a page with no permissions.
This is because I configured / role/findAllRoleList = perms ["role Management"] in the spring configuration file, and I have not authorized the current user, so the current user does not have permission to access this path
So to authorize the user, write the authorization method in the UserRealm class
/ / Authorization method @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) {SimpleAuthorizationInfo info = new SimpleAuthorizationInfo (); User user = (User) principals.getPrimaryPrincipal (); for (Role role: user.getRoles ()) {for (Privilege privilege: role.getPrivileges ()) {info.addStringPermission (privilege.getName ());} return info;}
In this way, it can be accessed normally, and the authorization method is automatically called by the shiro framework when the path / role/findAllRoleList is accessed.
We used to configure / role/findAllRoleList = perms ["role management"] in the spring configuration file, but now we introduce another way, which I prefer, to use annotations for permission control.
Using shiro's method to annotate access control
Step 1: enable shiro annotation support in the springmvc configuration file (Note: springmvc framework, put in the springmvc configuration file, struts in the spring configuration file)
Step 2: use the shiro annotation-@ RequiresPermissions ("") on the Controller method to execute this method with appropriate permissions
/ * query job list * / @ RequiresPermissions ("role list") / / this method must have role list permission @ RequestMapping ("/ findAllRoleList") public String findAllRoleList (Model model) {List roleList = roleService.findAllRoleList (); model.addAttribute ("roleList", roleList); return "role/list";}
@ RequiresAuthentication
Verifying that the user is logged in is the same as if the method subject.isAuthenticated () results in true.
@ RequiresUser
To verify whether the user is remembered, user has two meanings:
One is successfully logged in (subject.isAuthenticated () result is true)
The other is memorized (subject.isRemembered () result is true).
@ RequiresGuest
Verify that it is a guest request, as opposed to @ RequiresUser.
In other words, RequiresUser =! RequiresGuest .
At this time, the result of subject.getPrincipal () is null.
@ RequiresRoles
For example:
@ RequiresRoles ("aRoleName"); void someMethod ()
The method someMethod can only be accessed if there is an aRoleName role in the subject. If you do not have this permission, an exception AuthorizationException is thrown.
@ RequiresPermissions
For example:
@ RequiresPermissions ({"file:read", "write:aFile.txt"}) void someMethod ()
Requires that the subject must have the permissions of both file:read and write:aFile.txt to execute the method someMethod (). Otherwise, an exception AuthorizationException is thrown.
The permission control of the annotation method is completed, but when there is no permission limit, it will not automatically jump to the page without permission, but throw the exception directly to the page, so we need to configure a global exception handling.
Step 3: in the springmvc configuration file, configure the global exception capture as follows. When the shiro framework throws an exception with insufficient permissions, jump to the prompt page for insufficient permissions.
Redirect:/noPrivilegeUI.jsp
Use the page tag method provided by shiro to control permissions
Finally, talk about the page tags provided by shiro
Step 1: introduce shiro tag library into jsp pages
Step 2: use shiro tags to control the display of page elements
In this way, a shiro starter program is completed.
The above is all the content of this article "how to use the Apache shiro Framework". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.