@RequestMapping(value = "/checkUser",method= RequestMethod.POST) public @ResponseBody CommResult<Object> checkUser(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception { CommResult<Object> cr = new CommResult<Object>(); try { //random number String strData = request.getParameter( "strData" ); // encrypted random number String strSignedData = request.getParameter( "strSignedData" ); //B64 encoded public key certificate String strCertData = request.getParameter( "strCertData" ); //Verify the validity of the random number String certNumber = SecAuthUtil.getCertSN(strCertData);//ca serial number String certExpDate = SecAuthUtil.getCertExpDate(strCertData);//CA validity period CommResult cr2 = baseInterface.verifyCaSignData( strData, strSignedData, strCertData ); if (!cr2.isSuccess()) { return cr2; } String commonCapName = baseInterface.getCertCommonOrgName( strCertData ); // certificate common name UcenterOrgUserVo userOrgVo = new UcenterOrgUserVo(); userOrgVo.setCaCompName( commonCapName ); userOrgVo.setStatus( DicDataEnum.dataStatusValid.getId() ); UcenterOrgUserVo ucenterOrgUserVo = null; List<UcenterOrgUserVo> userVoList = this.ucenterOrgUserService.queryForList( userOrgVo ); if (!userVoList.isEmpty()) { this.baseInterface.updateCaNumber( userVoList.get( 0 ).getId(),strCertData ); } Subject currentUser = SecurityUtils.getSubject(); if (currentUser.isAuthenticated()) { currentUser.logout(); } UcenterUserVo userVo = this.ucenterUserService.getById( userVoList.get( 0 ).getUserId()); return dologin(currentUser, userVo, false ); } catch (Exception e) { cr.setSuccess(false); cr.setResult(CommResultEnum.ERROR,"Exception occurred!"); cr.setMsg( "Please check if the CA is bound!" ); log.error("Exception occurred!", e); return cr; } } private CommResult<Object> dologin(Subject currentUser,UcenterUserVo checkUser, boolean isCalogin) { CommResult<Object> cr = new CommResult<Object>(); CommResultEnum res = CommResultEnum.SUCCESS; UpmsToken token = new UpmsToken(checkUser.getAccount(), checkUser.getPassword(), isCalogin ? LoginType.USER_CA.getType() : LoginType.USER.getType()); try { TokenManager.login(token); } catch (LockedAccountException lae) { res = CommResultEnum.USER_ACCOUNT_IS_LOCKED; } catch (UnknownAccountException uae) { res = CommResultEnum.USER_INVALID_USERNAME_OR_PASS; } catch (IncorrectCredentialsException ice) { res = CommResultEnum.USER_INVALID_USERNAME_OR_PASS; } catch (AuthenticationException ae) { res = CommResultEnum.USER_INVALID_USERNAME_OR_PASS; } catch (Exception e) { res = CommResultEnum.ERROR; } cr.setResult( res ); return cr; }
public class UpmsToken extends UsernamePasswordToken { private String loginType; public UpmsToken(String username, String password, String loginType) { super(username, password); this.loginType = loginType; } public String getLoginType() { return this.loginType; } public void setLoginType(String loginType) { this.loginType = loginType; } }
realm associated database
public class CAUserRealm extends AuthorizingRealm { @Autowired public IUcenterRoleMenuService ucenterRoleMenuService; @Autowired public IUcenterUserService ucenterUserService; public CAUserRealm() { } protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { if (!SecurityUtils.getSubject().isAuthenticated()) { this.doClearCache(principalCollection); SecurityUtils.getSubject().logout(); return null; } else { Collection realms = principalCollection.fromRealm(this.getName()); if (realms.size() == 0) { return null; } else { String userId = ShiroKit.getUser().getId(); if (StringUtils.isBlank(userId)) { return null; } else { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); SecurityUcenterUserInfoVo securityUserInfoVo = this.ucenterRoleMenuService.querySecurityUserInfo(userId); info.addRoles (securityUserInfoVo.getRoleCodeList ()); info.addStringPermissions(securityUserInfoVo.getPermissions()); return info; } } } } protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException { UpmsToken token = (UpmsToken)authToken; UcenterUserVo user = this.ucenterUserService.getUserByAccount(token.getUsername()); if (user == null) { throw new UnknownAccountException("Account password error"); } else if (DicDataEnum.userLocked.getIntId().toString().equals(user.getStatus())) { throw new LockedAccountException("Account is locked"); } else if (DicDataEnum.userStop.getIntId().toString().equals(user.getStatus())) { throw new LockedAccountException("Account is disabled"); } else { UpmsShiroUser shiroUser = new UpmsShiroUser(); shiroUser.setAccount(user.getAccount()); shiroUser.setId(user.getId()); shiroUser.setLoginType (token.getLoginType ()); shiroUser.setOrgId(user.getOrgId()); shiroUser.setUserName(user.getUsername()); return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), this.getName()); } } public void clearCachedAuthorizationInfo() { PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals(); SimplePrincipalCollection principals = new SimplePrincipalCollection(principalCollection, this.getName()); super.clearCachedAuthorizationInfo(principals); } public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) { SimplePrincipalCollection principals = new SimplePrincipalCollection(principalCollection, this.getName()); super.clearCachedAuthorizationInfo(principals); } public boolean isPermitted(PrincipalCollection principals, String permission) { return super.isPermitted (principals, permission); } public String getName() { return LoginType.USER.toString(); } }
shiro gadget
public class ShiroKit { private static final String NAMES_DELIMETER = ","; public static final String hashAlgorithmName = "MD5"; public static final int hashIterations = 1024; public ShiroKit() { } public static String md5(String credentials, String saltSource) { ByteSource salt = new Md5Hash (saltSource); return (new SimpleHash("MD5", credentials, salt, 1024)).toString(); } public static String md5(String credentials) { return (new SimpleHash("MD5", credentials)).toString(); } public static String getRandomSalt(int length) { return RandomUtil.generateRandomString(length); } public static Subject getSubject() { return SecurityUtils.getSubject(); } public static boolean isUser() { return getSubject() != null && getSubject().getPrincipal() != null; } public static boolean isGuest() { return !isUser(); } public static UpmsShiroUser getUser() { return isGuest() ? null : (UpmsShiroUser)getSubject().getPrincipals().getPrimaryPrincipal(); } public static Session getSession() { return getSubject().getSession(); } public static <T> T getSessionAttr(String key) { Session session = getSession(); return session != null ? session.getAttribute(key) : null; } public static void setSessionAttr(String key, Object value) { Session session = getSession(); session.setAttribute(key, value); } public static void removeSessionAttr(String key) { Session session = getSession(); if (session != null) { session.removeAttribute(key); } } public static boolean hasRole(String roleName) { return getSubject() != null && roleName != null && roleName.length() > 0 && getSubject().hasRole(roleName); } public static boolean lacksRole(String roleName) { return !hasRole(roleName); } public static boolean hasAnyRoles(String roleNames) { boolean hasAnyRole = false; Subject subject = getSubject(); if (subject != null && roleNames != null && roleNames.length() > 0) { String[] var3 = roleNames.split(","); int var4 = var3.length; for(int var5 = 0; var5 < var4; ++var5) { String role = var3[var5]; if (subject.hasRole(role.trim())) { hasAnyRole = true; break; } } } return hasAnyRole; } public static boolean hasAllRoles(String roleNames) { boolean hasAllRole = true; Subject subject = getSubject(); if (subject != null && roleNames != null && roleNames.length() > 0) { String[] var3 = roleNames.split(","); int var4 = var3.length; for(int var5 = 0; var5 < var4; ++var5) { String role = var3[var5]; if (!subject.hasRole(role.trim())) { hasAllRole = false; break; } } } return hasAllRole; } public static boolean hasPermission(String permission) { return getSubject() != null && permission != null && permission.length() > 0 && getSubject().isPermitted(permission); } public static boolean lacksPermission(String permission) { return !hasPermission(permission); } public static boolean isAuthenticated() { return getSubject() != null && getSubject().isAuthenticated(); } public static boolean notAuthenticated() { return !isAuthenticated(); } public static String principal() { if (getSubject() != null) { Object principal = getSubject().getPrincipal(); return principal.toString(); } else { return ""; } } public static boolean isAjax(ServletRequest request) { return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest)request).getHeader("X-Requested-With")); } }
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="authenticator" ref="authenticator"/> <!-- Implementation of database login verification--> <property name="realms"> <list> <ref bean="ucenterUserRealm"/> <ref bean="caRealm"/> </list> </property> <!-- session manager --> <property name="sessionManager" ref="sessionManager"/> <!-- Cache Manager --> <property name="cacheManager" ref="upmsShiroCacheManager"/> </bean> <!-- Configure the use of a custom authenticator, which can achieve multi-Realm authentication, and can specify a specific Realm to handle a specific type of verification --> <bean id="authenticator" class="com.hisea.upms.security.shiro.pam.UpmsModularRealmAuthenticator"> <!-- Configure the authentication policy, as long as one Realm is successfully authenticated, and return all authentication success information--> <property name="authenticationStrategy"> <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean> </property> <!-- Implementation of database login verification--> <property name="realms"> <list> <ref bean="ucenterUserRealm"/> <ref bean="caRealm"/> </list> </property> </bean>