Shiro framework learning (3)

When using the shiro framework, you can inherit the AuthorizingRealm class and override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)和

protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) These two methods are used to implement login verification and permission acquisition.

 1 @Override
 2     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
 3         
 4         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
 5         String username = token.getUsername();
 6         Session session = UserUtils.getSession();
 7         session.setAttribute("loginFailType", null);
 8         session.setAttribute("loginFailMessage", null);
 9         int activeSessionSize = getSystemService().getSessionDao().getActiveSessions(false).size();
10                 User user = UserUtils.getByLoginName2(username);
11         if (user == null) {
 12              session.setAttribute("loginFailType", "UserNotExist");
 13              session.setAttribute("loginFailMessage", "The username does not exist, please enter a correct username.");
 14              throw new AuthenticationException("msg: The username does not exist, please enter a correct username.");
 15          }    
 16          String sessionid = user.getSessionid();
 17                  if (!Global.TRUE.equals(Global.getConfig("sameAccountLogin") ) && !"1".equals(user.getId())){
 18              Collection < Session > sessions = getSystemService().getSessionDao().getActiveSessions(true, null, session);
19             if (sessions != null && sessions.size() > 0){
20                 for (Session sessioni : sessions){
21                     Object siid = sessioni.getId();
22                     if(siid.equals(sessionid)){
23                                                 getSystemService().getSessionDao().delete(sessioni);
24                     }
25                                     }                
26             }
27         }
28                 int    maxSessionSize = Integer.valueOf(Global.getConfig("maxSessionSize"));         
29         if(activeSessionSize > maxSessionSize){
30              session.setAttribute("loginFailType", "usersOverload");
 31              session.setAttribute("loginFailMessage", "Too many logins, the server is busy, please try again later.");
 32              throw new AuthenticationException("msg:login Too many people, the server is busy, please try again later.");
 33          }
 34          if (logger.isDebugEnabled()){
 35              logger.debug("login submit, active session size: {}, username: {}", activeSessionSize, username);
 36          }            
 37                  if (Global.TRUE.equals(Global.getConfig("validateCodeLogin")) && LoginController.isValidateCodeLogin(username, false, false)){
 38             String code = (String)session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
39             if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)){
40                 session.setAttribute("loginFailType", "verificationCodeError");
41                 session.setAttribute("loginFailMessage", "验证码错误, 请重试.");
42                 throw new AuthenticationException("msg:验证码错误, 请重试.");
43             }
44         }
45         
46                 String message = UserUtils.isForbidLogin(username);
47         if (StringUtils.isNoneBlank(message)){
48                 session.setAttribute("loginFailType", "forbidLogin");
49                 session.setAttribute("loginFailMessage", message);
50                 throw new AuthenticationException("msg:"+message,new Throwable());
51         }
52                 return new SimpleAuthenticationInfo(new Principal(user, token.isMobileLogin()),
53                 user.getPassword().toLowerCase(), getName());
54 
55     }
56     }
1  /** 
2       * Get the authorization information, if it exists in the cache, get it directly from the cache, otherwise get it again, call after successful login
 3       */ 
4      protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
 5          if (principals == null ) {
 6              return  null ;
 7          }
 8          
9          AuthorizationInfo info = null ;
 10  
11          info = (AuthorizationInfo)UserUtils.getCache(UserUtils.CACHE_AUTH_INFO);
 12  
13          if (info == null ) {
 14              info =doGetAuthorizationInfo(principals);
 15              if (info != null ) {
 16                  UserUtils.putCache(UserUtils.CACHE_AUTH_INFO, info);
 17              }
 18          }
 19  
20          return info;
 21      }
 22  
23      /** 
24       * Authorization query callback function, go 25       */ 
26      @Override
 27      protected AuthorizationInfo doGetAuthorizationInfo
 (PrincipalCollection principals) {
 28          Principal principal = (Principal) getAvailablePrincipal(principals);
 29         // Get the currently logged in user 
30          if (!Global.TRUE.equals(Global.getConfig("user.multiAccountLogin" ))){
 31              Collection<Session> sessions = getSystemService().getSessionDao().getActiveSessions( true , principal, UserUtils.getSession());
 32              if (sessions.size() > 0 ){
 33                  // If logged in, kick out the online user 
34                  if (UserUtils.getSubject().isAuthenticated()){
 35                      for (Session session : sessions){
 36                          getSystemService().getSessionDao().delete(session);
 37                      }
 38                  }
39                  // Remember that I came in, and the current user is logged in, then exit the current user prompt. 
40                  else {
 41                      UserUtils.getSubject().logout();
 42                      throw  new AuthenticationException("msg: The account has been logged in elsewhere, please log in again." );
 43                  }
 44              }
 45          }
 46          User user = getSystemService(). getUserByLoginName(principal.getLoginName());
 47          if (user != null ) {
 48              SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
 49              List<Menu> list =UserUtils.getMenuList();
 50              for (Menu menu : list){
 51                  if (StringUtils.isNotBlank(menu.getPermission())){
 52                      // Add permission information based on Permission 
53                      for (String permission : StringUtils.split(menu .getPermission(),"," )){
 54                          info.addStringPermission(permission);
 55                      }
 56                  }
 57              }
 58              // Add user permission 
59              info.addStringPermission("user" );
 60              // Add user role information 
61              for(Role role : user.getRoleList()){
 62                  info.addRole(role.getEnname());
 63              }
 64              // Update login IP and time 
65              getSystemService().updateUserLoginInfo(user);
 66              // Record login log 
67              LogUtils.saveLog(Servlets.getRequest(), "System Logon" );
 68              return info;
 69          } else {
 70              return  null ;
 71          }
 72      }

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324733995&siteId=291194637