In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
Dependency package org.apache.shiro shiro-spring 1.3.2 database table
Keep everything simple, user user table, and role role table
Shiro related class Shiro configuration class @ Configurationpublic class ShiroConfig {@ Bean public ShiroFilterFactoryBean shirFilter (SecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean (); / / SecurityManager shiroFilterFactoryBean.setSecurityManager (securityManager) must be set; / / if setLoginUrl is not set, it automatically looks for the "/ login.jsp" page under the root directory of the Web project or the "/ login" mapping shiroFilterFactoryBean.setLoginUrl ("/ notLogin"). / / set url; shiroFilterFactoryBean.setUnauthorizedUrl for unlimited time hopping ("/ notRole"); / / set interceptor Map filterChainDefinitionMap = new LinkedHashMap (); / / visitors, development permission filterChainDefinitionMap.put ("/ guest/**", "anon") / / user, requires role permission "user" filterChainDefinitionMap.put ("/ user/**", "roles [user]"); / / administrator, requires role permission "admin" filterChainDefinitionMap.put ("/ admin/**", "roles [admin]"); / / Open login interface filterChainDefinitionMap.put ("/ login", "anon") / / all other interfaces must be intercepted / / the main line of code must be placed at the end of all permission settings, otherwise all url will be intercepted filterChainDefinitionMap.put ("/ * *", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap (filterChainDefinitionMap); System.out.println ("Shiro interceptor factory class injection successful"); return shiroFilterFactoryBean } / * inject securityManager * / @ Bean public SecurityManager securityManager () {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager (); / / set realm. SecurityManager.setRealm (customRealm ()); return securityManager;} / * Custom Authentication realm; *
* you must write this class with @ Bean annotation in order to inject CustomRealm, * otherwise it will affect the dependency injection of other classes in the CustomRealm class * / @ Bean public CustomRealm customRealm () {return new CustomRealm ();}}
Note: the SecurityManager class in it should import import org.apache.shiro.mgt.SecurityManager;, but if you are copying the code, it will import java.lang.SecurityManager by default. There is also a slight hole here, and other classes also belong to the classes in the shiro package.
The shirFilter method mainly sets some important jump url, such as unauthorized time-limited jump when not logged in, and the permission interception of all kinds of url, such as user permission is required for url starting with / user, admin permission is required for url starting with / admin, etc.
Permission to intercept Filter
When running a Web application, Shiro will create some useful default Filter instances and automatically make them available, and these default Filter instances are defined by the DefaultFilter enumeration class, of course, we can also customize the Filter instance, which will be discussed in future articles
Filter explains that anon has no parameters and open permissions, which can be understood as anonymous users or tourists who have no access to authc and need to verify that logout has no parameters, log out, and jump directly to shiroFilterFactoryBean.setLoginUrl () after execution. The set urlauthcBasic has no parameter, which means that httpBasic authentication user has no parameter, which means that there must be a user. If you do not check ssl without parameter during login operation, it means a secure URL request. The protocol is that httpsperms [user] parameters can be written more than one, indicating that one or some permissions are required to pass. Write perms ["user, admin"] when there are multiple parameters. When there are multiple parameters, each parameter must be passed before passing the roles [admin] parameter. Indicates that only one or some roles can pass, and write roles ["admin,user"] when there are multiple parameters. When there are multiple parameters, each parameter must be passed through rest [user] according to the requested method, which is equivalent to perms [user:method], where method is port such as post,get,delete [8081] when the requested URL port is not 8081, jump to schemal://serverName:8081?queryString where schmal is protocol http or https, etc., serverName is the Host you visit 8081 is the Port port, and the queryString is from the URL you visited? The following parameters
The most commonly used ones are anon,authc,user,roles,perms and so on.
Note: anon, authc, authcBasic and user are the first set of authentication filters. Perms, port, rest, roles and ssl are the second set of authorization filters. To pass the authorization filter, you must first complete the login authentication operation (that is, you must complete the authentication before looking for authorization) before you can use the second group of authorizers (such as accessing url that requires roles permission. If you haven't logged in yet, you will jump to shiroFilterFactoryBean.setLoginUrl (); set url).
Customize the realm class
First of all, we have to inherit the AuthorizingRealm class to customize our own realm to carry out our custom identity and authority authentication operations.
Remember to ask Override to override the doGetAuthenticationInfo and doGetAuthorizationInfo methods (the names of the two methods are very similar, make no mistake)
Public class CustomRealm extends AuthorizingRealm {private UserMapper userMapper; @ Autowired private void setUserMapper (UserMapper userMapper) {this.userMapper = userMapper;} / * * get authentication information * in Shiro, the user, role and permission information in the application is finally obtained through Realm. * * @ param authenticationToken user identity information token * @ return returns the AuthenticationInfo instance * / @ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println ("- authentication method -"); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken / / String password = userMapper.getPassword (token.getUsername ()); if (null = = password) {throw new AccountException ("incorrect user name");} else if (! password.equals (new String ((char []) token.getCredentials () {throw new AccountException ("incorrect password") } return new SimpleAuthenticationInfo (token.getPrincipal (), password, getName ());} / * * obtain authorization information * * @ param principalCollection * @ return * / @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {System.out.println ("- permission authentication -"); String username = (String) SecurityUtils.getSubject () .getPrincipal () SimpleAuthorizationInfo info = new SimpleAuthorizationInfo (); / / get the user role String role = userMapper.getRole (username); Set set = new HashSet (); / / need to encapsulate role into Set as the parameter set.add (role) of info.setRoles (); / / set the role info.setRoles (set) owned by the user; return info;}}
The two methods of rewriting are identity authentication and permission authentication respectively. In shiro, there is a Subject.login () method for login operation. When we pass in the token encapsulating the user name and password as a parameter, we will run into these two methods (not necessarily both methods will enter)
The doGetAuthorizationInfo method will only enter when permission authentication is required. For example, the administrator role of filterChainDefinitionMap.put ("/ admin/**", "roles [admin]") configured in the previous configuration class will enter the doGetAuthorizationInfo method to check permissions when entering / admin, while the doGetAuthenticationInfo method will only enter when identity authentication is required (such as the previous Subject.login () method).
Turning to the UsernamePasswordToken class, we can get the login user name and password from this object (new UsernamePasswordToken (username, password) will be used when logging in, while the get user name or password can be used in the following ways
Token.getUsername () / / get the user name Stringtoken.getPrincipal () / / get the user name Object token.getPassword () / / get the password char [] token.getCredentials () / / get the password Object
Note: many people will find that the interface of UserMapper and other classes cannot be injected through @ Autowired, and will report NullPointerException when running the program. There are many reasons on the Internet, such as the loading order of Spring, but there is actually a very important point to note. CustomRealm is set in the securityManager.setRealm () method of the shiro configuration class, and many people directly write securityManager.setRealm (new CustomRealm ()). This will not work, you must use @ Bean to inject MyRealm, and you cannot directly new the object:
@ Bean public SecurityManager securityManager () {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager (); / / set realm. SecurityManager.setRealm (customRealm ()); return securityManager;} @ Bean public CustomRealm customRealm () {return new CustomRealm ();}
The reason is also very simple, just like calling Service in Controller, it's all SpringBean, so you can't new yourself.
Of course, the same truth can be written as follows:
@ Bean public SecurityManager securityManager (CustomRealm customRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager (); / / set realm. SecurityManager.setRealm (customRealm); return securityManager;}
Then simply add a @ Component annotation to the CustomRealm class
Function realization
All the functions of this paper are implemented by returning json data from the interface.
Assign controller tourists @ RestController@RequestMapping ("/ guest") public class GuestController {@ Autowired private final ResultMap resultMap; @ RequestMapping (value = "/ enter", method = RequestMethod.GET) public ResultMap login () {return resultMap.success () .message ("Welcome in, your identity is a tourist") according to the permission of return resultMap.success. } @ RequestMapping (value = "/ getMessage", method = RequestMethod.GET) public ResultMap submitLogin () {return resultMap.success () .message ("you have access to information about this interface!") ;} ordinary login user @ RestController@RequestMapping ("/ user") public class UserController {@ Autowired private final ResultMap resultMap; @ RequestMapping (value = "/ getMessage", method = RequestMethod.GET) public ResultMap getMessage () {return resultMap.success () .message ("you have user rights, you can get information about this interface!") Administrator @ RestController@RequestMapping ("/ admin") public class AdminController {@ Autowired private final ResultMap resultMap; @ RequestMapping (value = "/ getMessage", method = RequestMethod.GET) public ResultMap getMessage () {return resultMap.success () .message ("you have administrator permission to get information about this interface!") ;}}
Suddenly noticed that an AccountException exception was thrown from the CustomRealm class, and now build a class to catch the exception
@ RestControllerAdvicepublic class ExceptionController {private final ResultMap resultMap; @ Autowired public ExceptionController (ResultMap resultMap) {this.resultMap = resultMap;} / / catch the exception @ ExceptionHandler (AccountException.class) public ResultMap handleShiroException (Exception ex) {return resultMap.fail (). Message (ex.getMessage ());}}
There is also LoginController for login and other processing.
@ RestControllerpublic class LoginController {@ Autowired private ResultMap resultMap; private UserMapper userMapper; @ RequestMapping (value = "/ notLogin", method = RequestMethod.GET) public ResultMap notLogin () {return resultMap.success () .message ("you haven't logged in yet!") ;} @ RequestMapping (value = "/ notRole", method = RequestMethod.GET) public ResultMap notRole () {return resultMap.success () .message ("you don't have permission!") ;} @ RequestMapping (value = "/ logout", method = RequestMethod.GET) public ResultMap logout () {Subject subject = SecurityUtils.getSubject (); / / logout subject.logout (); return resultMap.success () .message ("logged out successfully!") ;} / * * Log in * * @ param username username * @ param password password * / @ RequestMapping (value = "/ login", method = RequestMethod.POST) public ResultMap login (String username, String password) {/ / create a subject Subject subject = SecurityUtils.getSubject () from SecurityUtils / / prepare token (token) UsernamePasswordToken token = new UsernamePasswordToken (username, password) before authentication submission; / / execute authentication login subject.login (token); / / specify return data String role = userMapper.getRole (username) according to permissions; if ("user" .equals (role)) {return resultMap.success () .message ("Welcome to login") } if ("admin" .equals (role)) {return resultMap.success () .message ("Welcome to the administrator page");} return resultMap.fail () .message ("permission error!") ;} test
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.