org.apache.shiro.authc.ExcessiveAttemptsException Java Examples
The following examples show how to use
org.apache.shiro.authc.ExcessiveAttemptsException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SystemLoginController.java From cms with Apache License 2.0 | 6 votes |
@RequestMapping(value = "${web.adminPath}/login", method = RequestMethod.POST) public String showLoginForm(HttpServletRequest request, Model model) { String error = null; String exceptionClassName = (String)request.getAttribute(FormAuthenticationCaptchaFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if(AccountException.class.getName().equals(exceptionClassName)){ error = "对不起,您输入用户名"; } else if(UnknownAccountException.class.getName().equals(exceptionClassName)){ error = "对不起,您输入用户名不存在"; } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){ error = "对不起,您输入用户名/密码错误"; } else if(CaptchaException.class.getName().equals(exceptionClassName)) { error="对不起,您输入验证码错误"; } else if(LockedAccountException.class.getName().equals(exceptionClassName)) { error="对不起,您账号被冻结,请联系管理员"; } else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)){ error="重复密码错误超过5次,请等待30分钟..."; }else if(exceptionClassName != null) { error = "登录系统错误"; } model.addAttribute("error", error); return getRemoteView("login_signin"); // return "redirect:/"+getTemplate()+"/login"; }
Example #2
Source File: LoginController.java From cms with Apache License 2.0 | 6 votes |
@RequestMapping(value = "login", method = RequestMethod.POST) public String showLoginForm(HttpServletRequest request, Model model) { String error = null; String exceptionClassName = (String)request.getAttribute(FormAuthenticationCaptchaFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if(AccountException.class.getName().equals(exceptionClassName)){ error = "对不起,您输入用户名"; } else if(UnknownAccountException.class.getName().equals(exceptionClassName)){ error = "对不起,您输入用户名不存在"; } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){ error = "对不起,您输入用户名/密码错误"; } else if(CaptchaException.class.getName().equals(exceptionClassName)) { error="对不起,您输入验证码错误"; } else if(LockedAccountException.class.getName().equals(exceptionClassName)) { error="对不起,您账号被冻结,请联系管理员"; } else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)){ error="重复密码错误超过5次,请等待30分钟..."; }else if(exceptionClassName != null) { error = "登录系统错误"; } model.addAttribute("error", error); return getRemoteView("login"); // return "redirect:/"+getTemplate()+"/login"; }
Example #3
Source File: FormAuthenticationWithLockFilter.java From DWSurvey with GNU Affero General Public License v3.0 | 6 votes |
@Override public boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { AuthenticationToken token = createToken(request, response); if (token == null) { String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " + "must be created in order to execute a login attempt."; throw new IllegalStateException(msg); } if (checkIfAccountLocked(request)) { return onLoginFailure(token, new ExcessiveAttemptsException(), request, response); } else { if (!doLogin(request, response, token)) { resetAccountLock(getUsername(request)); return false; } return true; } }
Example #4
Source File: ApiServiceImpl.java From wangmarket with Apache License 2.0 | 6 votes |
public UserVO identityVerifyAndSession(String key) { UserVO vo = identityVerify(key); if(vo.getResult() - UserVO.FAILURE == 0){ return vo; } UsernamePasswordToken token = new UsernamePasswordToken(vo.getUser().getUsername(), vo.getUser().getUsername()); token.setRememberMe(false); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); } catch ( UnknownAccountException uae ) { uae.printStackTrace(); } catch ( IncorrectCredentialsException ice ) { ice.printStackTrace(); } catch ( LockedAccountException lae ) { lae.printStackTrace(); } catch ( ExcessiveAttemptsException eae ) { eae.printStackTrace(); } catch ( org.apache.shiro.authc.AuthenticationException ae ) { ae.printStackTrace(); } return vo; }
Example #5
Source File: MainController.java From jboot-admin with Apache License 2.0 | 5 votes |
@Before( {POST.class, LoginValidator.class} ) public void postLogin() { String loginName = getPara("loginName"); String pwd = getPara("password"); MuitiLoginToken token = new MuitiLoginToken(loginName, pwd); Subject subject = SecurityUtils.getSubject(); RestResult<String> restResult = new RestResult<String>(); restResult.success().setMsg("登录成功"); try { if (!subject.isAuthenticated()) { token.setRememberMe(false); subject.login(token); User u = userService.findByName(loginName); subject.getSession(true).setAttribute(Consts.SESSION_USER, u); } if (getParaToBoolean("rememberMe") != null && getParaToBoolean("rememberMe")) { setCookie("loginName", loginName, 60 * 60 * 24 * 7); } else { removeCookie("loginName"); } } catch (UnknownAccountException une) { restResult.error("用户名不存在"); } catch (LockedAccountException lae) { restResult.error("用户被锁定"); } catch (IncorrectCredentialsException ine) { restResult.error("用户名或密码不正确"); } catch (ExcessiveAttemptsException exe) { restResult.error("账户密码错误次数过多,账户已被限制登录1小时"); } catch (Exception e) { e.printStackTrace(); restResult.error("服务异常,请稍后重试"); } renderJson(restResult); }
Example #6
Source File: WebExceptionHandler.java From Shiro-Action with MIT License | 5 votes |
@ExceptionHandler public String excessiveAttemptsException(ExcessiveAttemptsException e) { if (log.isDebugEnabled()) { log.debug("登录失败次数过多"); } return generateErrorInfo(ResultBean.FAIL, "登录失败次数过多, 请稍后再试"); }
Example #7
Source File: SysLoginController.java From mumu with Apache License 2.0 | 5 votes |
/** * 用户登录 * @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); }
Example #8
Source File: RetryLimitHashedCredentialsMatcher.java From mumu with Apache License 2.0 | 5 votes |
/** * 做认证匹配 */ @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { //获取缓存key String loginName=(String) token.getPrincipal(); String cacheName=getCacheName(loginName); // retry count + 1 String retryCount=jedisClient.get(cacheName); if (retryCount == null) { //缓存两小时 jedisClient.incr(cacheName); jedisClient.expire(cacheName,60*60*2); }else{ int counter=Integer.parseInt(retryCount); if(counter<5){ jedisClient.incr(cacheName); }else{ throw new ExcessiveAttemptsException(); } } if(loginCredentialsHandler!=null){ loginCredentialsHandler.before(); } boolean matches = super.doCredentialsMatch(token, info); if (matches) { // clear retry count jedisClient.del(cacheName); //用户认证成功之后 进行相关操作 if(loginCredentialsHandler!=null){ loginCredentialsHandler.after(); } }else{ SysUser unloginUser=new SysUser(); unloginUser.setUserName(loginName); unloginUser.setPassword(token.getCredentials().toString()); SecurityUtils.getSubject().getSession(true).setAttribute(SysUser.SYS_USER, unloginUser); } return matches; }
Example #9
Source File: UserServiceImpl.java From wangmarket with Apache License 2.0 | 4 votes |
public BaseVO loginByUsernameAndPassword(HttpServletRequest request, String username, String password){ username = Safety.filter(username); BaseVO baseVO = new BaseVO(); if(username==null || username.length() == 0 ){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserOrEmailNotNull")); return baseVO; } if(password==null || password.length() == 0){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginPasswordNotNull")); return baseVO; } //判断是用户名还是邮箱登陆的,进而查询邮箱或者用户名,进行登录 List<User> l = sqlDAO.findByProperty(User.class, username.indexOf("@")>-1? "email":"username", username); if(l!=null && l.size()>0){ User user = l.get(0); String md5Password = new Md5Hash(password, user.getSalt(),Global.USER_PASSWORD_SALT_NUMBER).toString(); //检验密码是否正确 if(md5Password.equals(user.getPassword())){ //检验此用户状态是否正常,是否被冻结 if(user.getIsfreeze() == User.ISFREEZE_FREEZE){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze")); return baseVO; } user.setLasttime(DateUtil.timeForUnix10()); user.setLastip(IpUtil.getIpAddress(request)); sqlDAO.save(user); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername()); token.setRememberMe(false); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); } catch ( UnknownAccountException uae ) { java.lang.System.out.println("UnknownAccountException:"+uae.getMessage()); } catch ( IncorrectCredentialsException ice ) { java.lang.System.out.println("IncorrectCredentialsException:"+ice.getMessage()); } catch ( LockedAccountException lae ) { java.lang.System.out.println("LockedAccountException:"+lae.getMessage()); } catch ( ExcessiveAttemptsException eae ) { java.lang.System.out.println("ExcessiveAttemptsException:"+eae.getMessage()); } catch ( org.apache.shiro.authc.AuthenticationException ae ) { java.lang.System.out.println("AuthenticationException:"+ae.getMessage()); } // logDao.insert("USER_LOGIN_SUCCESS"); baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess")); }else{ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginPasswordFailure")); } }else{ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserNotFind")); } return baseVO; }
Example #10
Source File: LoginServlet.java From opensoc-streaming with Apache License 2.0 | 4 votes |
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username" ); String password = req.getParameter("password" ); UsernamePasswordToken token = new UsernamePasswordToken(username, password); logger.info( "Doing login for user: " + username ); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); } catch ( UnknownAccountException uae ) { logger.warn( "Failing login with 401:", uae ); resp.sendError(405); return; } catch ( IncorrectCredentialsException ice ) { logger.warn( "Failing login with 401:", ice ); resp.sendError(405); return; } catch ( LockedAccountException lae ) { logger.warn( "Failing login with 401:", lae ); resp.sendError(401); return; } catch ( ExcessiveAttemptsException eae ) { logger.warn( "Failing login with 401:", eae ); resp.sendError(401); return; } catch ( AuthenticationException ae ) { logger.warn( "Failing login with 401:", ae ); resp.sendError(401); return; } if( currentUser.hasRole("ShiroUsersRole") ) { try { Cookie authTokenCookie = new Cookie("authToken", AuthToken.generateToken(configProps)); resp.addCookie(authTokenCookie); // resp.setStatus(HttpServletResponse.SC_OK); resp.sendRedirect( "/withsocket.jsp" ); } catch( Exception e ) { logger.error( "Failed creating authToken cookie.", e ); resp.sendError( 500 ); return; } } else { logger.error("User does not have required role!"); resp.sendError(401); return; } }
Example #11
Source File: UserServiceImpl.java From wangmarket with Apache License 2.0 | 4 votes |
public BaseVO loginForUserId(HttpServletRequest request, int userId) { BaseVO baseVO = new BaseVO(); User user = sqlDAO.findById(User.class, userId); if(user == null){ Log.debug("用户不存在"); baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneUserNotFind")); return baseVO; } //检验此用户状态是否正常,是否被冻结 if(user.getIsfreeze() == User.ISFREEZE_FREEZE){ Log.debug("此用户被冻结,无法设置为登陆用户"); baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze")); return baseVO; } /*******更改User状态******/ user.setLasttime(DateUtil.timeForUnix10()); user.setLastip(IpUtil.getIpAddress(request)); sqlDAO.save(user); Log.debug("设置指定userId为登陆用户,设置后得User:"+user); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername()); token.setRememberMe(false); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); } catch ( UnknownAccountException uae ) { uae.printStackTrace(); } catch ( IncorrectCredentialsException ice ) { ice.printStackTrace(); } catch ( LockedAccountException lae ) { lae.printStackTrace(); } catch ( ExcessiveAttemptsException eae ) { eae.printStackTrace(); } catch ( org.apache.shiro.authc.AuthenticationException ae ) { ae.printStackTrace(); } // logDao.insert("USER_LOGIN_SUCCESS"); baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess")); return baseVO; }
Example #12
Source File: UserServiceImpl.java From wangmarket with Apache License 2.0 | 4 votes |
public BaseVO loginByUserid(HttpServletRequest request, int userid) { BaseVO baseVO = new BaseVO(); User user = sqlDAO.findById(User.class, userid); if(user == null){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneUserNotFind")); return baseVO; } //ip检测 String ip = IpUtil.getIpAddress(request); if(!(user.getLastip().equals(ip) || user.getRegip().equals(ip))){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneIpFailure")); return baseVO; } //检验此用户状态是否正常,是否被冻结 if(user.getIsfreeze() == User.ISFREEZE_FREEZE){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze")); return baseVO; } /*******更改User状态******/ user.setLasttime(DateUtil.timeForUnix10()); user.setLastip(IpUtil.getIpAddress(request)); sqlDAO.save(user); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername()); token.setRememberMe(false); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); } catch ( UnknownAccountException uae ) { uae.printStackTrace(); } catch ( IncorrectCredentialsException ice ) { ice.printStackTrace(); } catch ( LockedAccountException lae ) { lae.printStackTrace(); } catch ( ExcessiveAttemptsException eae ) { eae.printStackTrace(); } catch ( org.apache.shiro.authc.AuthenticationException ae ) { ae.printStackTrace(); } // logDao.insert("USER_LOGIN_SUCCESS"); baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess")); return baseVO; }
Example #13
Source File: UserServiceImpl.java From wangmarket with Apache License 2.0 | 4 votes |
/** * 手机号登陆,会自动检测上次登陆的ip,若上次登陆的ip跟当前的ip一样,则这个手机用户登陆成功 * @param request {@link HttpServletRequest} * <br/>登陆时form表单需提交两个参数:phone(手机号)、code(手机收到的动态验证码) * @return {@link BaseVO} */ public BaseVO loginByPhone(HttpServletRequest request) { BaseVO baseVO = new BaseVO(); String phone = Safety.filter(request.getParameter("phone")); if(phone==null){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhonePhoneFailure")); return baseVO; }else{ phone = phone.replaceAll(" ", ""); if(phone.length() != 11){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhonePhoneFailure")); return baseVO; } } User user = findByPhone(phone); if(user == null){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneUserNotFind")); return baseVO; } //ip检测 String ip = IpUtil.getIpAddress(request); if(!(user.getLastip().equals(ip) || user.getRegip().equals(ip))){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneIpFailure")); return baseVO; } //检验此用户状态是否正常,是否被冻结 if(user.getIsfreeze() == User.ISFREEZE_FREEZE){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze")); return baseVO; } Log.debug("检验此用户状态是否正常,是否被冻结,未冻结,正常"); /*******更改User状态******/ user.setLasttime(DateUtil.timeForUnix10()); user.setLastip(IpUtil.getIpAddress(request)); sqlDAO.save(user); Log.debug("更新User状态,更新后的User为:"+user); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername()); token.setRememberMe(false); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); } catch ( UnknownAccountException uae ) { uae.printStackTrace(); } catch ( IncorrectCredentialsException ice ) { ice.printStackTrace(); } catch ( LockedAccountException lae ) { lae.printStackTrace(); } catch ( ExcessiveAttemptsException eae ) { eae.printStackTrace(); } catch ( org.apache.shiro.authc.AuthenticationException ae ) { ae.printStackTrace(); } // logDao.insert("USER_LOGIN_SUCCESS"); baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess")); return baseVO; }
Example #14
Source File: UserServiceImpl.java From wangmarket with Apache License 2.0 | 4 votes |
/** * 手机号+动态验证码登陆 * @param request {@link HttpServletRequest} * <br/>登陆时form表单需提交两个参数:phone(手机号)、code(手机收到的动态验证码) * @return {@link BaseVO} */ public BaseVO loginByPhoneAndCode(HttpServletRequest request) { BaseVO baseVO = new BaseVO(); String phone = Safety.filter(request.getParameter("phone")); String code = Safety.filter(request.getParameter("code")); if(phone==null || phone.length() != 11){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneAndCodePhoneFailure")); return baseVO; } if(code==null || code.length() != 6){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneAndCodeCodeFailure")); return baseVO; } int queryAddtime = 0; if(SmsLog.codeValidity > 0){ int currentTime = DateUtil.timeForUnix10(); queryAddtime = currentTime-SmsLog.codeValidity; } SmsLog smsLog = findByPhoneAddtimeUsedTypeCode(phone, queryAddtime, SmsLog.USED_FALSE, SmsLog.TYPE_LOGIN,code); if(smsLog != null){ User user = findByPhone(phone); int userid = 0; if(user != null && user.getId() != null){ userid = user.getId(); } /****更改SmsLog状态*****/ smsLog.setUserid(userid); smsLog.setUsed(SmsLog.USED_TRUE); sqlDAO.save(smsLog); //如果没有用户,则直接返回失败提示 if(user == null){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneAndCodeRegFailure")); return baseVO; } //检验此用户状态是否正常,是否被冻结 if(user.getIsfreeze() == User.ISFREEZE_FREEZE){ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginUserFreeze")); return baseVO; } /*******更改User状态******/ user.setLasttime(DateUtil.timeForUnix10()); user.setLastip(IpUtil.getIpAddress(request)); sqlDAO.save(user); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getUsername()); token.setRememberMe(false); Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); } catch ( UnknownAccountException uae ) { uae.printStackTrace(); } catch ( IncorrectCredentialsException ice ) { ice.printStackTrace(); } catch ( LockedAccountException lae ) { lae.printStackTrace(); } catch ( ExcessiveAttemptsException eae ) { eae.printStackTrace(); } catch ( org.apache.shiro.authc.AuthenticationException ae ) { ae.printStackTrace(); } // logDao.insert("USER_LOGIN_SUCCESS"); baseVO.setBaseVO(BaseVO.SUCCESS, Language.show("user_loginSuccess")); return baseVO; }else{ baseVO.setBaseVO(BaseVO.FAILURE, Language.show("user_loginByPhoneAndCodeCodeNotFind")); return baseVO; } }
Example #15
Source File: RetryLimitCredentialsMatcher.java From springboot-learn with MIT License | 4 votes |
@Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { System.out.println("=================RetryLimitCredentialsMatcher.doCredentialsMatch================="); User shiroUser = (User) info.getPrincipals().getPrimaryPrincipal(); Long userId = shiroUser.getId(); User user = userService.getByPrimaryKey(userId); String username = user.getUsername(); // 访问一次,计数一次 String loginCountKey = SHIRO_LOGIN_COUNT + username; String isLockKey = SHIRO_IS_LOCK + username; countMap.put(loginCountKey, 1); if (countMap.get(loginCountKey) > 5) { throw new ExcessiveAttemptsException("帐号[" + username + "]已被禁止登录!"); } // 计数大于5时,设置用户被锁定一小时 Integer loginCount = countMap.get(loginCountKey); int retryCount = (5 - loginCount); if (retryCount <= 0) { throw new ExcessiveAttemptsException("由于密码输入错误次数过多,帐号[" + username + "]已被禁止登录!"); } boolean matches = super.doCredentialsMatch(token, info); if (!matches) { String msg = retryCount <= 0 ? "您的账号一小时内禁止登录!" : "您还剩" + retryCount + "次重试的机会"; throw new AccountException("帐号或密码不正确!" + msg); } //清空登录计数 countMap.remove(loginCountKey); try { userService.updateUserLastLoginInfo(user); } catch (Exception e) { e.printStackTrace(); } // 当验证都通过后,把用户信息放在session里 // 注:User必须实现序列化 SecurityUtils.getSubject().getSession().setAttribute(CommonConstants.USER_SESSION_KEY, user); return true; }
Example #16
Source File: UserController.java From demo-springmvc-shiro with Apache License 2.0 | 4 votes |
@RequestMapping(value="/login", method=RequestMethod.POST) public String login(String username, String password, HttpServletRequest request){ System.out.println("-------------------------------------------------------"); String rand = (String)request.getSession().getAttribute("rand"); String captcha = WebUtils.getCleanParam(request, "captcha"); System.out.println("用户["+username+"]登录时输入的验证码为["+captcha+"],HttpSession中的验证码为["+rand+"]"); if(!StringUtils.equals(rand, captcha)){ request.setAttribute("message_login", "验证码不正确"); return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/"; } UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(true); System.out.print("为验证登录用户而封装的Token:"); System.out.println(ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); //获取当前的Subject Subject currentUser = SecurityUtils.getSubject(); try { //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查 //每个Realm都能在必要时对提交的AuthenticationTokens作出反应 //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法 System.out.println("对用户[" + username + "]进行登录验证...验证开始"); currentUser.login(token); System.out.println("对用户[" + username + "]进行登录验证...验证通过"); }catch(UnknownAccountException uae){ System.out.println("对用户[" + username + "]进行登录验证...验证未通过,未知账户"); request.setAttribute("message_login", "未知账户"); }catch(IncorrectCredentialsException ice){ System.out.println("对用户[" + username + "]进行登录验证...验证未通过,错误的凭证"); request.setAttribute("message_login", "密码不正确"); }catch(LockedAccountException lae){ System.out.println("对用户[" + username + "]进行登录验证...验证未通过,账户已锁定"); request.setAttribute("message_login", "账户已锁定"); }catch(ExcessiveAttemptsException eae){ System.out.println("对用户[" + username + "]进行登录验证...验证未通过,错误次数过多"); request.setAttribute("message_login", "用户名或密码错误次数过多"); }catch(AuthenticationException ae){ //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景 System.out.println("对用户[" + username + "]进行登录验证...验证未通过,堆栈轨迹如下"); ae.printStackTrace(); request.setAttribute("message_login", "用户名或密码不正确"); } //验证是否登录成功 if(currentUser.isAuthenticated()){ System.out.println("用户[" + username + "]登录认证通过(这里可进行一些认证通过后的系统参数初始化操作)"); return "main"; }else{ token.clear(); return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/"; } }
Example #17
Source File: RestController.java From springboot-shiro-cas-mybatis with MIT License | 4 votes |
/** * 前后端分离的情况之下rest风格登录获取TGT ST * @Description:TODO * @author:hsj qq:2356899074 * @time:2017年12月1日 下午2:49:40 * @param req * @param respon * @return * @throws Exception */ @RequestMapping("/restlogin") public String restlogin(HttpServletRequest req,HttpServletResponse respon)throws Exception{ // return RestFulLogin.validateFromCAS("hsjhsj", "hsjhsj"); //校验有没有username和password String username = "hsjhsj"; UsernamePasswordToken token = new UsernamePasswordToken("hsjhsj","hsjhsj"); //获取当前的Subject Subject currentUser = SecurityUtils.getSubject(); try { //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查 //每个Realm都能在必要时对提交的AuthenticationTokens作出反应 //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法 logger.info("对用户[" + username + "]进行登录验证..验证开始"); currentUser.login(token); logger.info("对用户[" + username + "]进行登录验证..验证通过"); }catch(UnknownAccountException uae){ logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户"); return "403"; }catch(IncorrectCredentialsException ice){ logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证"); return "403"; }catch(LockedAccountException lae){ logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定"); return "403"; }catch(ExcessiveAttemptsException eae){ logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多"); return "403"; }catch(AuthenticationException ae){ //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景 logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下"); ae.printStackTrace(); return "403"; } //验证是否登录成功 if(currentUser.isAuthenticated()){ logger.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)"); return "inde"; }else{ token.clear(); return "403"; } }
Example #18
Source File: RetryLimitCredentialsMatcher.java From OneBlog with GNU General Public License v3.0 | 4 votes |
@Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { Long userId = (Long) info.getPrincipals().getPrimaryPrincipal(); User user = userService.getByPrimaryKey(userId); String username = user.getUsername(); // 访问一次,计数一次 ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); String loginCountKey = SHIRO_LOGIN_COUNT + username; String isLockKey = SHIRO_IS_LOCK + username; opsForValue.increment(loginCountKey, 1); if (redisTemplate.hasKey(isLockKey)) { String unit = "分钟"; long time = TimeUnit.SECONDS.toMinutes(redisTemplate.getExpire(isLockKey)); if (time <= 0) { unit = "秒"; time = TimeUnit.SECONDS.toSeconds(redisTemplate.getExpire(isLockKey)); } else if (time > 60) { unit = "小时"; time = TimeUnit.SECONDS.toHours(redisTemplate.getExpire(isLockKey)); } throw new ExcessiveAttemptsException("帐号[" + username + "]已被禁止登录!剩余" + time + unit); } Map<String, Object> configs = configService.getConfigs(); Object loginRetryNumObj = configs.get("loginRetryNum"); Object sessionTimeOutObj = configs.get("sessionTimeOut"); Object sessionTimeOutUnitObj = configs.get("sessionTimeOutUnit"); int loginRetryNum = StringUtils.isEmpty(loginRetryNumObj) ? DEFAULT_RETRY_NUM : Integer.parseInt(String.valueOf(loginRetryNumObj)); int sessionTimeOut = StringUtils.isEmpty(sessionTimeOutObj) ? DEFAULT_SESSIONTIME_OUT : Integer.parseInt(String.valueOf(sessionTimeOutObj)); TimeUnit sessionTimeOutUnit = StringUtils.isEmpty(sessionTimeOutUnitObj) ? DEFAULT_SESSIONTIME_OUT_UNIT : TimeUnit.valueOf(String.valueOf(sessionTimeOutUnitObj)); String loginCount = String.valueOf(opsForValue.get(loginCountKey)); int retryCount = ((loginRetryNum + 1) - Integer.parseInt(loginCount)); if (retryCount <= 0) { opsForValue.set(isLockKey, "LOCK"); redisTemplate.expire(isLockKey, sessionTimeOut, sessionTimeOutUnit); redisTemplate.expire(loginCountKey, sessionTimeOut, sessionTimeOutUnit); throw new ExcessiveAttemptsException("由于密码输入错误次数过多,帐号[" + username + "]已被禁止登录!"); } boolean matches = super.doCredentialsMatch(token, info); if (!matches) { throw new AccountException("帐号或密码不正确!您还剩" + retryCount + "次重试的机会"); } //清空登录计数 redisTemplate.delete(loginCountKey); try { userService.updateUserLastLoginInfo(user); } catch (Exception e) { e.printStackTrace(); } // 当验证都通过后,把用户信息放在session里 // 注:User必须实现序列化 SecurityUtils.getSubject().getSession().setAttribute(SessionConst.USER_SESSION_KEY, user); return true; }
Example #19
Source File: RetryLimitCredentialsMatcher.java From springboot-shiro with MIT License | 4 votes |
@Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { Long userId = (Long) info.getPrincipals().getPrimaryPrincipal(); User user = userService.getByPrimaryKey(userId); String username = user.getUsername(); // 访问一次,计数一次 ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); String loginCountKey = SHIRO_LOGIN_COUNT + username; String isLockKey = SHIRO_IS_LOCK + username; opsForValue.increment(loginCountKey, 1); if (redisTemplate.hasKey(isLockKey)) { throw new ExcessiveAttemptsException("帐号[" + username + "]已被禁止登录!"); } // 计数大于5时,设置用户被锁定一小时 String loginCount = String.valueOf(opsForValue.get(loginCountKey)); int retryCount = (5 - Integer.parseInt(loginCount)); if (retryCount <= 0) { opsForValue.set(isLockKey, "LOCK"); redisTemplate.expire(isLockKey, 1, TimeUnit.HOURS); redisTemplate.expire(loginCountKey, 1, TimeUnit.HOURS); throw new ExcessiveAttemptsException("由于密码输入错误次数过多,帐号[" + username + "]已被禁止登录!"); } boolean matches = super.doCredentialsMatch(token, info); if (!matches) { String msg = retryCount <= 0 ? "您的账号一小时内禁止登录!" : "您还剩" + retryCount + "次重试的机会"; throw new AccountException("帐号或密码不正确!" + msg); } //清空登录计数 redisTemplate.delete(loginCountKey); try { userService.updateUserLastLoginInfo(user); } catch (Exception e) { e.printStackTrace(); } // 当验证都通过后,把用户信息放在session里 // 注:User必须实现序列化 SecurityUtils.getSubject().getSession().setAttribute(SessionConst.USER_SESSION_KEY, user); return true; }