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 > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use Java to integrate Shiro to achieve user login authentication function", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use Java to integrate Shiro to achieve user login authentication function" bar!
Content:
For Shiro, I believe you should have heard of it, and even used it! To put it simply, it is a very useful framework for user identity authentication and authorization, which can realize the functions of user login authentication, authority, resource authorization, session management and so on. In this second kill system, we will mainly use this framework to achieve user identity authentication and user login functions.
It is worth mentioning that the "Shiro to achieve user login authentication" function module introduced in this blog involves the database table user, which is the user information table.
Org.apache.shiro shiro-ehcache ${shiro.version} org.apache.shiro shiro-core ${shiro.version} org.apache.shiro shiro-web ${shiro.version} org.apache.shiro shiro-spring ${shiro.version}
(2) the functional methods corresponding to user login, user login and user logout requests are developed in the UserController controller. The complete source code is as follows:
Autowiredprivate Environment env; / / Jump to the login page @ RequestMapping (value = {"/ to/login", "/ unauth"}) public String toLogin () {return "login";} / / login authentication @ RequestMapping (value = "/ login", method = RequestMethod.POST) public String login (@ RequestParam String userName, @ RequestParam String password, ModelMap modelMap) {String errorMsg= "" Try {if (! SecurityUtils.getSubject (). IsAuthenticated ()) {String newPsd=new Md5Hash (password,env.getProperty ("shiro.encrypt.password.salt")) .toString (); UsernamePasswordToken token=new UsernamePasswordToken (userName,newPsd); SecurityUtils.getSubject () .login (token);}} catch (UnknownAccountException e) {errorMsg=e.getMessage (); modelMap.addAttribute ("userName", userName) } catch (DisabledAccountException e) {errorMsg=e.getMessage (); modelMap.addAttribute ("userName", userName);} catch (IncorrectCredentialsException e) {errorMsg=e.getMessage (); modelMap.addAttribute ("userName", userName);} catch (Exception e) {errorMsg= "user login exception, please contact the administrator!"; e.printStackTrace () } if (StringUtils.isBlank (errorMsg)) {return "redirect:/index";} else {modelMap.addAttribute ("errorMsg", errorMsg); return "login";}} / / log in @ RequestMapping (value = "/ logout") public String logout () {SecurityUtils.getSubject (). Logout (); return "login";}
Among them, when matching the user's password, we use the Md5Hash method here, that is, MD5 encryption (because the user's password field in the user table of the database is stored in the encrypted string encrypted by MD5)
The content of the front-end page login.jsp is relatively simple, and only requires the user to enter the most basic user name and password, as shown in the following figure is part of the core source code of the page:
When the front end submits a "user login" request, the user name and password will be submitted to the login method corresponding to the back-end UserController controller in the form of "submit form". This method will first perform the most basic parameter judgment and verification, and after the verification is passed, the Shiro built-in component SecurityUtils.getSubject (). Login () method will be called to perform the login operation, in which the login operation will be mainly performed in the "custom Realm doGetAuthenticationInfo method".
(3) the next step is to develop a custom Realm based on the AuthorizingRealm of Shiro, and implement the user login authentication method, namely the doGetAuthenticationInfo () method. The complete source code is as follows:
/ * * user-defined realm- for shiro authentication, authorization * @ Author:debug (SteadyJack) * @ Date: 17:55 on 2019-7-2 * * / public class CustomRealm extends AuthorizingRealm {private static final Logger log= LoggerFactory.getLogger (CustomRealm.class); private static final Long sessionKeyTimeOut=3600_000L; @ Autowired private UserMapper userMapper; / / Authorization @ Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {return null } / / Authentication-Log in @ Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authenticationToken) throws AuthenticationException {UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken; String userName=token.getUsername (); String password=String.valueOf (token.getPassword ()); log.info ("currently logged in user name = {} password = {}", userName,password); User user=userMapper.selectByUserName (userName) If (user==null) {throw new UnknownAccountException ("username does not exist!");} if (! Objects.equals (1MagneUser.getIsActive (). IntValue () {throw new DisabledAccountException ("current user has been disabled!");} if (! user.getPassword (). Equals (password)) {throw new IncorrectCredentialsException ("username password does not match!") } SimpleAuthenticationInfo info=new SimpleAuthenticationInfo (user.getUserName (), password,getName ()); setSession ("uid", user.getId ()); return info } / * insert key and the corresponding value into the session of shiro-finally hand it over to HttpSession for management (if it is a distributed session configuration, it is to be managed by redis) * @ param key * @ param value * / private void setSession (String key,Object value) {Session session=SecurityUtils.getSubject (). GetSession (); if (sessionkeeper null) {session.setAttribute (key,value) Session.setTimeout (sessionKeyTimeOut);}
Among them, userMapper.selectByUserName (userName) is mainly used to query user entity information according to userName, and its corresponding dynamic Sql is written as follows:
SELECT FROM user WHERE user_name = # {userName}
It is worth mentioning that when the user logs in successfully (that is, the values of the user name and password match the user table of the database), we will use Shiro's Session session mechanism to store the current user's information in the server session and cache it for a certain period of time! (here is 3600s, that is, 1 hour)!
(4) finally, we need to implement "how to automatically detect whether the user is logged in when accessing the details of the product to be killed or snapping up the product or any business request that needs to be intercepted? if you have logged in, go directly to the method logic corresponding to the business request, otherwise, you need to go to the user login page to require the user to log in."
Based on this requirement, we need to use ShiroFilterFactoryBean, a component of Shiro, to determine whether a user is logged in or not, and to intercept some URL links that require authorization with FilterChainDefinitionMap. The complete source code is as follows:
/ * * Universal configuration of shiro * @ Author:debug (SteadyJack) * @ Date: 17:54 on 2019-7-2 * * / @ Configurationpublic class ShiroConfig {@ Bean public CustomRealm customRealm () {return new CustomRealm ();} @ Bean public SecurityManager securityManager () {DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager (); securityManager.setRealm (customRealm ()); securityManager.setRememberMeManager (null); return securityManager } @ Bean public ShiroFilterFactoryBean shiroFilterFactoryBean () {ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean (); bean.setSecurityManager (securityManager ()); bean.setLoginUrl ("/ to/login"); bean.setUnauthorizedUrl ("/ unauth"); / / intercept Map filterChainDefinitionMap=new HashMap () for some authorized links URL; filterChainDefinitionMap.put ("/ to/login", "anon") FilterChainDefinitionMap.put ("/ * *", "anon"); filterChainDefinitionMap.put ("/ kill/execute", "authc"); filterChainDefinitionMap.put ("/ item/detail/*", "authc"); bean.setFilterChainDefinitionMap (filterChainDefinitionMap); return bean;}}
As can be seen from the above source code, the ShiroFilterFactoryBean component of Shiro will intercept the links between URL=/kill/execute and URL=/item/detail/*, that is, when the user visits these URL, the system will require the current user to log in (if the user has not logged in yet! If you are already logged in, skip it directly and enter the actual business module! )
In addition, the ShiroFilterFactoryBean component of Shiro also sets links to "go to the login page" and "adjustment page without user authorization / login", which are / to/login and / unauth!
(5) at this point, the actual operation of the front and back end codes for integrating the Shiro framework to achieve user login authentication has been completed. Run the project / system in an external tomcat server, open the browser to access the "list page of products to be killed", and click "details". At this time, because the user has not yet logged in, the project / system will be redirected to the user login page, as shown below:
Enter user name: debug, password: 123456, click "Login" button, you can log in successfully, and successfully enter the "details page", as shown below:
After the login is successful, go back to the previous list page, that is, the list page of products to be killed, and click the details button again, which will directly enter the details page of products to be killed, instead of jumping to the user login page. And the user's login status will last for 1 hour! This is done with the help of Shiro's Session.
Thank you for your reading, the above is the content of "how to use Java to integrate Shiro to achieve user login authentication". After the study of this article, I believe you have a deeper understanding of how to use Java to integrate Shiro to achieve user login authentication, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.