@RequestMapping(value = "/member/login", method = RequestMethod.POST) public ResponseEntity login(HttpServletRequest request, Model model){ Map<String, Object> result = new HashMap<>(); if(SecurityUtils.getSubject().isAuthenticated()){ String username = (String) SecurityUtils.getSubject().getPrincipal(); result.put("status", 200); result.put("username", username); return new ResponseEntity(result, HttpStatus.OK); } String exceptionClassName = (String) request.getAttribute(FormAuthenticationFilterExt.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); String error = null; RestError restError = new RestError(); restError.setTimestamp(new Date()); if(DisabledAccountException.class.getName().equals(exceptionClassName)){ restError.setMessage("该账号已被锁定,请联系客服。"); }else if(UnknownAccountException.class.getName().equals(exceptionClassName)) { restError.setMessage("用户名不存在"); } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) { restError.setMessage("用户名或密码错误"); } else if(exceptionClassName != null) { restError.setMessage( "登录失败:" + exceptionClassName); } restError.setStatus(401); return new ResponseEntity(restError, HttpStatus.UNAUTHORIZED); }
protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) { String errorMessage = null; if (ae instanceof IncorrectCredentialsException) { errorMessage = "密码错误,输入错误超过当日限制,将锁定账户"; // 登录失败日志记录 logLoginStatus(request, LoginType.登录失败); } else if (ae instanceof ValidateCodeException) { errorMessage = "验证码错误"; } else if (ae instanceof UnValidationAccountException) { errorMessage = "账号未被验证"; } else if (ae instanceof LockedAccountException) { errorMessage = "密码输入错误超过当日限制,请明天再试"; } else if (ae instanceof DisabledAccountException) { errorMessage = "账号被管理员锁定"; } else if (ae instanceof UnknownAccountException) { errorMessage = "账号不存在"; } else { errorMessage = "未知错误"; log.fatal("登录错误-未知错误,请管理员检查", ae); } request.setAttribute(getFailureKeyAttribute(), errorMessage); }
/** * 登录认证,失败会捕获相关异常信息 */ protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) createToken(request, response); try { doCaptchaValidate( (HttpServletRequest)request,token); if(token.getUsername().equals("NO")){ throw new DisabledAccountException("该用户被禁用,请联系客服!"); } Subject subject = getSubject(request, response); subject.login(token); HttpSession session = ((HttpServletRequest) request).getSession(false); Member member = (Member) subject.getPrincipal(); session.setAttribute("currentMember", member); session.setAttribute("currentMemberWork", memberService.getMemberWork(member.getMemberId())); int messageNoticCount = loginTotalMessageNotic(member.getMemberId()); session.setAttribute("messageNoticCount", messageNoticCount); memberService.updateIntegra(member.getMemberId()); return onLoginSuccess(token, subject, request, response); } catch (AuthenticationException e) { return onLoginFailure(token, e, request, response); } }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken; String username = token.getUsername(); if (null != username && !"".equals(username)) { UserExample userExample = new UserExample(); userExample.createCriteria().andUsernameEqualTo(username); User principalUser = userMapper.selectByExample(userExample).get(0); if (null != principalUser) { // 用户状态为启用或隐藏让其通过认证 byte[] salt = Encodes.decodeHex(principalUser.getSalt()); AuthenticationInfo info = new SimpleAuthenticationInfo(principalUser, principalUser.getPassword(), ByteSource.Util.bytes(salt), getName());// 将用户的所有信息作为认证对象返回 clearCache(info.getPrincipals());// 认证成功后清除之前的缓存 updatePrincipalUserInfo(token, principalUser);// 更新用户登录信息 return info; } else { throw new DisabledAccountException(); } } return null; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken; String username = token.getUsername(); if (null != username && !"".equals(username)) { MemberTokenExample memberTokenExample = new MemberTokenExample(); memberTokenExample.createCriteria().andUsernameEqualTo(username); MemberToken tokenMember= memberTokenMapper.selectByExample(memberTokenExample).get(0); if (null != tokenMember) { // 用户状态为启用或隐藏让其通过认证 byte[] salt = Encodes.decodeHex(tokenMember.getSalt()); //通过会员id来获取会员信息 Member principalMember = memberMapper.selectByPrimaryKey(tokenMember.getMemberId()); AuthenticationInfo info = new SimpleAuthenticationInfo(principalMember, tokenMember.getPassword(), ByteSource.Util.bytes(salt), getName());// 将用户的所有信息作为认证对象返回 clearCache(info.getPrincipals());// 认证成功后清除之前的缓存 updatePrincipalMemberInfo(token, principalMember);// 更新用户登录信息 return info; } else { throw new DisabledAccountException(); } } return null; }
/** * 用户登录的身份验证方法 * */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String username = usernamePasswordToken.getUsername(); if (username == null) { throw new AccountException("用户名不能为空"); } User user = accountManager.getUserByUsername(username); if (user == null) { throw new UnknownAccountException("用户不存在"); } if (user.getState().equals(State.Disable.getValue())) { throw new DisabledAccountException("你的账户已被禁用,请联系管理员开通."); } SessionVariable model = new SessionVariable(user); return new SimpleAuthenticationInfo(model,user.getPassword(),getName()); }
/** * 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; User user = accountService.findUserByLoginName(token.getUsername()); if (user != null) { if (user.getStatus().equals("disabled")) { throw new DisabledAccountException(); } byte[] salt = Encodes.decodeHex(user.getSalt()); return new SimpleAuthenticationInfo(new ShiroUser(user.getLoginName(), user.getName()), user.getPassword(), ByteSource.Util.bytes(salt), getName()); } else { return null; } }
/** * 查询获得用户信息 AuthenticationToken 用于收集用户提交的身份(如用户名)及凭据(如密码) * * AuthenticationInfo有两个作用: 1、如果Realm 是AuthenticatingRealm * 子类,则提供给AuthenticatingRealm 内部使用的 * CredentialsMatcher进行凭据验证;(如果没有继承它需要在自己的Realm中自己实现验证); * 2、提供给SecurityManager来创建Subject(提供身份信息); * * @param authcToken * @return * @throws org.apache.shiro.authc.AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UserPasswordToken token = (UserPasswordToken) authcToken; String username = token.getUsername(); String password = new String(token.getPassword()); String ip = token.getHost(); if (username != null && password != null) { User user = userService.findByUser(new User(username)); if (user == null) { throw new UnknownAccountException(); } else if (user.getDisabled() != null && user.getDisabled()) { // 用户禁用状态 true:禁用 ,false:有效 throw new DisabledAccountException(); } else if (user.getLocked() != null && user.getLocked()) { // 用户锁定状态 true:锁定,false:未锁定 throw new LockedAccountException(); } else { // 密码校验 if (!DigestUtils.md5Hex(password).equals(user.getPassword())) { throw new IncorrectCredentialsException(); } } return new SimpleAuthenticationInfo(new Principal(user.getId(), username, ip), password, getName()); } throw new UnknownAccountException(); }
/** * 用户登录 * @return */ @MumuLog(name = "用户登录",operater = "POST") @RequestMapping(value = "/login",method = {RequestMethod.POST}) public ModelAndView logining(HttpServletRequest request){ String exceptionClassName = (String) request.getAttribute("shiroLoginFailure"); String error = null; if (UnknownAccountException.class.getName().equals(exceptionClassName)) { error = "用户名/密码错误"; } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) { error = "用户名/密码错误"; } else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)){ error = "输入错误次数太过,请稍后重试"; } else if(DisabledAccountException.class.getName().equals(exceptionClassName)){ error="账户被锁定,请联系管理员"; }else if(AccountUnActiveException.class.getName().equals(exceptionClassName)){ error="账户未激活,请登录邮箱激活账号!"; }else if (exceptionClassName != null) { error = "错误提示:" + exceptionClassName; } Map<String,String> map=new HashMap<String,String>(); if(error!=null){ request.setAttribute("shiroLoginFailure", error); map.put("code","500"); map.put("msg","failure"); map.put("data",error); return new ModelAndView("login",map); } map.put("code","200"); map.put("msg","success"); map.put("data","登录成功"); return new ModelAndView("redirect:/system/index",map); }
@Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { if (WebHelper.isAjax((HttpServletRequest) request)) { Result result = Result.failure(); if (e instanceof IncorrectCredentialsException) { result.message("密码错误"); } else if (e instanceof ExpiredCredentialsException) { result.message("密码已过期"); } else if (e instanceof UnknownAccountException) { result.message("该账号不存在"); } else if (e instanceof DisabledAccountException) { result.message("该账号已禁用"); } else if (e instanceof LockedAccountException) { result.message("该账号已锁定"); } else if (e instanceof AccountException) { result.message("账号错误"); } else if (e instanceof CredentialsException) { result.message("密码错误"); } try { writeObject(request, response, result); } catch (IOException ex) { throw new RuntimeException(ex); } return false; } return super.onLoginFailure(token, e, request, response); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) { UsernamePasswordToken upToken = (UsernamePasswordToken) token; CUser user; try { user = configuration.readUser(upToken.getUsername()); } catch (UserNotFoundException e) { throw new AccountException("User '" + upToken.getUsername() + "' cannot be retrieved.", e); } if (user.getPassword() == null) { throw new AccountException("User '" + upToken.getUsername() + "' has no password, cannot authenticate."); } if (CUser.STATUS_ACTIVE.equals(user.getStatus())) { // Check for legacy user that has unsalted password hash // Update if unsalted password hash and valid credentials were specified if (hasLegacyPassword(user) && isValidCredentials(upToken, user)) { reHashPassword(user, new String(upToken.getPassword())); } return createAuthenticationInfo(user); } else if (CUser.STATUS_DISABLED.equals(user.getStatus())) { throw new DisabledAccountException("User '" + upToken.getUsername() + "' is disabled."); } else { throw new AccountException( "User '" + upToken.getUsername() + "' is in illegal status '" + user.getStatus() + "'."); } }
/** * 获取认证信息 * * @param token * 令牌 * @return 认证信息 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken token) { AuthenticationToken authenticationToken = (AuthenticationToken) token; String username = authenticationToken.getUsername(); String password = new String(authenticationToken.getPassword()); String captchaId = authenticationToken.getCaptchaId(); String captcha = authenticationToken.getCaptcha(); String ip = authenticationToken.getHost(); if (!captchaService.isValid(CaptchaType.adminLogin, captchaId, captcha)) { throw new UnsupportedTokenException(); } if (username != null && password != null) { Admin admin = adminService.findByUsername(username); if (admin == null) { throw new UnknownAccountException(); } if (!admin.getIsEnabled()) { throw new DisabledAccountException(); } Setting setting = SettingUtils.get(); if (admin.getIsLocked()) { if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.admin)) { int loginFailureLockTime = setting.getAccountLockTime(); if (loginFailureLockTime == 0) { throw new LockedAccountException(); } Date lockedDate = admin.getLockedDate(); Date unlockDate = DateUtils.addMinutes(lockedDate, loginFailureLockTime); if (new Date().after(unlockDate)) { admin.setLoginFailureCount(0); admin.setIsLocked(false); admin.setLockedDate(null); adminService.update(admin); } else { throw new LockedAccountException(); } } else { admin.setLoginFailureCount(0); admin.setIsLocked(false); admin.setLockedDate(null); adminService.update(admin); } } if (!DigestUtils.md5Hex(password).equals(admin.getPassword())) { int loginFailureCount = admin.getLoginFailureCount() + 1; if (loginFailureCount >= setting.getAccountLockCount()) { admin.setIsLocked(true); admin.setLockedDate(new Date()); } admin.setLoginFailureCount(loginFailureCount); adminService.update(admin); throw new IncorrectCredentialsException(); } admin.setLoginIp(ip); admin.setLoginDate(new Date()); admin.setLoginFailureCount(0); adminService.update(admin); return new SimpleAuthenticationInfo(new Principal(admin.getId(), username), password, getName()); } throw new UnknownAccountException(); }
/** * 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { SystemLoginToken token = (SystemLoginToken) authcToken; if (token.getUsername() == null) { throw new AccountException("提交表单未包含用户名."); } // 增加判断验证码逻辑 String captcha = token.getCaptcha(); String exitCode = (String) SecurityUtils .getSubject() .getSession() .getAttribute( com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if (null == captcha || !captcha.equalsIgnoreCase(exitCode)) { throw new ValidateCodeException("验证码错误"); } UserLoginDto user = userservice.login(token.getUsername()); if (user == null) { return null; } log.info("[用户登录]-[获取登录用户信息]-返回数据结果:" + ToStringBuilder.reflectionToString(user)); if (user != null && UserConstant.SUCCESS == user.getResult()) { // 用户没有被验证 if (!user.isvStatus()) { log.info("用户没有通过邮箱验证."); throw new UnValidationAccountException(); } if(user.isDisable()&&UserDisableReason.登录超过限制.equals(user.getDisableReason())){ throw new LockedAccountException(); } // 用户被锁定 if (user.isDisable()) { log.info("用户被禁止登录."); throw new DisabledAccountException(); } byte[] salt = Encodes.decodeHex(user.getSalt()); return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getName(), user.getRole()), user.getPassword(), ByteSource.Util.bytes(salt), getName()); } throw new UnknownAccountException(); }
/** * Method description * * * @param ar * * @return */ private Set<String> authenticate(AuthenticationResult ar) { Set<String> groupSet = null; User user = ar.getUser(); try { groupSet = createGroupSet(ar); // check for admin user checkForAuthenticatedAdmin(user, groupSet); // store user User dbUser = userDAO.get(user.getName()); if (dbUser != null) { checkDBForAdmin(user, dbUser); checkDBForActive(user, dbUser); } // we assume that the user has logged in through the web-interface // before, // thus we ommit the creation process. if (user.isActive()) { if (logger.isDebugEnabled()) { logGroups(user, groupSet); } } else { String msg = "user ".concat(user.getName()).concat( " is deactivated"); if (logger.isWarnEnabled()) { logger.warn(msg); } throw new DisabledAccountException(msg); } } catch (Exception ex) { logger.error("authentication failed", ex); throw new AuthenticationException("authentication failed", ex); } return groupSet; }
/** * Method description * * * @param password * @param ar * * @return */ private Set<String> authenticate(String password, AuthenticationResult ar) { Set<String> groupSet = null; User user = ar.getUser(); try { groupSet = createGroupSet(ar); // check for admin user checkForAuthenticatedAdmin(user, groupSet); // store user User dbUser = userDAO.get(user.getName()); if (dbUser != null) { checkDBForAdmin(user, dbUser); checkDBForActive(user, dbUser); } else if (!user.isValid() && logger.isErrorEnabled()) { logger.error( "could not create user {}, beacause it is not valid", user.getName()); } if (user.isActive()) { if (logger.isDebugEnabled()) { logGroups(user, groupSet); } // store encrypted credentials in session String credentials = user.getName(); if (Util.isNotEmpty(password)) { credentials = credentials.concat(":").concat(password); } credentials = CipherUtil.getInstance().encode(credentials); } else { String msg = "user ".concat(user.getName()).concat( " is deactivated"); if (logger.isWarnEnabled()) { logger.warn(msg); } throw new DisabledAccountException(msg); } } catch (Exception ex) { logger.error("authentication failed", ex); throw new AuthenticationException("authentication failed", ex); } return groupSet; }