@Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws ExcessiveAttemptsException { String username = (String)token.getPrincipal(); AtomicInteger retryCount = passwordRetryCache.get(username); if(retryCount == null) { retryCount = new AtomicInteger(0); passwordRetryCache.put(username, retryCount); } if(retryCount.incrementAndGet() > retryMax) { throw new ExcessiveAttemptsException("您已连续错误达" + retryMax + "次!请10分钟后再试"); } boolean matches = super.doCredentialsMatch(token, info); if(matches) { passwordRetryCache.remove(username); }else { throw new IncorrectCredentialsException("密码错误,已错误" + retryCount.get() + "次,最多错误" + retryMax + "次"); } return true; }
@RequestMapping(value = "/login", method = { RequestMethod.POST}) public String dashboard(ModelMap map, Admin admin) { String error = null; UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword()); token.setRememberMe(false); try { SecurityUtils.getSubject().login(token); return "redirect:/video/all"; } catch (UnknownAccountException uae) { error = "用户名错误!"; } catch (IncorrectCredentialsException ice) { error = "密码错误!"; } catch (LockedAccountException lae) { error = "用户被锁定!"; } map.addAttribute("error", error); return "login.ftl"; }
@RequestMapping(value = "/login") public String showLoginForm(HttpServletRequest req, Model model) { if(req.getMethod().equalsIgnoreCase("get")){ return "login"; } String exceptionClassName = (String)req.getAttribute("shiroLoginFailure"); String error = null; if(UnknownAccountException.class.getName().equals(exceptionClassName)) { error = "用户名/密码错误"; } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) { error = "用户名/密码错误"; } else if(exceptionClassName != null) { error = "其他错误:" + exceptionClassName; } if(error!=null){ model.addAttribute("shiroLoginFailure", error); return "login"; } return "redirect:/main"; }
public boolean tryLogin(String email, String password, Boolean rememberMe) { org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(email, password); token.setRememberMe(rememberMe); try { currentUser.login(token); System.out.println("User [" + currentUser.getPrincipal().toString() + "] logged in successfully."); // save username in the session currentUser.getSession().setAttribute("username", email); return true; } catch (UnknownAccountException uae) { System.out.println("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { System.out.println("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { System.out.println("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } return false; }
@RequestMapping("/login") public String login(HttpServletRequest request) throws Exception{ String exceptionClassName = (String) request.getAttribute("shiroLoginFailure"); //根据shiro返回的异常类路径判断,抛出指定异常信息 if(exceptionClassName!=null){ if (UnknownAccountException.class.getName().equals(exceptionClassName)) { //最终会抛给异常处理器 throw new UnknownAccountException("账号不存在"); } else if (IncorrectCredentialsException.class.getName().equals( exceptionClassName)) { throw new IncorrectCredentialsException("用户名/密码错误"); }else { throw new Exception();//最终在异常处理器生成未知错误 } } return "login"; }
/** * 登录失败调用事件 */ @Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { String className = e.getClass().getName(), message = ""; if (IncorrectCredentialsException.class.getName().equals(className) || UnknownAccountException.class.getName().equals(className)){ message = "用户或密码错误, 请重试."; } else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){ message = StringUtils.replace(e.getMessage(), "msg:", ""); } else{ message = "系统出现点问题,请稍后再试!"; e.printStackTrace(); // 输出到控制台 } request.setAttribute(getFailureKeyAttribute(), className); request.setAttribute(getMessageParam(), message); return true; }
@RequestMapping(value = "/signin", method = { RequestMethod.POST}) public String signin(ModelMap map, User user, HttpServletRequest request) { String error; UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPasswd()); token.setRememberMe(null != request.getParameter("rememberme") ? true : false); try { Subject subject = SecurityUtils.getSubject(); subject.login(token); subject.getSession().setAttribute("curUser", userService.findByUsername((String) subject.getPrincipal())); return "redirect:/dashboard/console"; } catch (UnknownAccountException uae) { error = "用户名错误!"; } catch (IncorrectCredentialsException ice) { error = "密码错误!"; } catch (LockedAccountException lae) { error = "用户被锁定!"; } map.addAttribute("error", error); return "signin"; }
@RequestMapping(value = "/changepwd", method = { RequestMethod.POST}) public String changepwd(ModelMap map, User user, @RequestParam(value = "passwdnew", required = true) String passwdnew) { //验证当前账号 UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPasswd()); token.setRememberMe(false); try { SecurityUtils.getSubject().login(token); //验证通过更新用户密码 user.setId(getCurrentUser().getId()); user.setPasswd(passwdnew); passwordHelper.encryptPassword(user); userService.updateById(user); return "redirect:/dashboard/console"; } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) { map.addAttribute("exception", e.getMessage()); return "common/error"; } }
/** * 登录失败调用事件 */ @Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { String className = e.getClass().getName(), message = ""; if (IncorrectCredentialsException.class.getName().equals(className) || UnknownAccountException.class.getName().equals(className)) { message = "用户或密码错误, 请重试."; } else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")) { message = StringUtils.replace(e.getMessage(), "msg:", ""); } else { message = "系统出现点问题,请稍后再试!"; e.printStackTrace(); // 输出到控制台 } request.setAttribute(getFailureKeyAttribute(), className); request.setAttribute(getMessageParam(), message); return true; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String phoneNumber = (String)token.getPrincipal(); if(StringUtils.trimToNull(phoneNumber) == null){ throw new IncorrectCredentialsException();//账号或密码错误 } CdMember query = new CdMember(); query.setPhoneNumber(phoneNumber); CdMember member = memberService.findMember(query); if(member == null) { throw new UnknownAccountException();//没找到帐号 } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( phoneNumber, //用户名 member.getPassword(), //密码 ByteSource.Util.bytes(AppConstants.PC_PASSWORD_SALT),//salt=phoneNumber getName() //realm name ); return authenticationInfo; }
@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); }
@RequestMapping(value = "/login") public String login(HttpServletRequest request, Model model){ if(SecurityUtils.getSubject().isAuthenticated()){ return "redirect:/"; } 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(exceptionClassName != null) { error = "其他错误:" + exceptionClassName; } model.addAttribute("error", error); return "login"; }
@POST @Path("login") public Response login(@NotNull @FormParam("username") String username, @NotNull @FormParam("password") String password, @NotNull @FormParam("rememberMe") boolean rememberMe, @Context HttpServletRequest request) { boolean justLogged = SecurityUtils.getSubject().isAuthenticated(); try { SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, rememberMe)); } catch (Exception e) { throw new IncorrectCredentialsException("Unknown user, please try again"); } SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request); monitoring.fire(new AuthenticationEvent(username, AuthenticationEvent.Type.LOGIN)); if (savedRequest != null) { return this.getRedirectResponse(savedRequest.getRequestUrl(), request); } else { if (justLogged) { return this.getRedirectResponse(WebPages.DASHBOARD_URL, request); } return this.getRedirectResponse(WebPages.HOME_URL, request); } }
@RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public Result<User> login(String username, String password) throws IOException { // response.setHeader("resetCookie", "true"); if (TextUtil.isEmpty(username) || TextUtil.isEmpty(password)) { return new Result<User>(false, "用户名或密码为空", null); } Result<User> result; try { User returnUser = accountService.login(username, password); if (returnUser != null) { // response.setHeader("resetCookie", "true"); result = new Result<User>(true, null, returnUser); } else { result = new Result<User>(false, "登录失败.", null); } } catch (IncorrectCredentialsException e) { result = new Result<User>(false, "帐号密码错误", null); } catch (UnknownAccountException e1) { result = new Result<User>(false, "帐号密码错误", null); } return result; }
protected RouteBuilder createRouteBuilder() throws Exception { final ShiroSecurityPolicy securityPolicy = new ShiroSecurityPolicy("./src/test/resources/securityconfig.ini", passPhrase, false); return new RouteBuilder() { @SuppressWarnings("unchecked") public void configure() { onException(UnknownAccountException.class, IncorrectCredentialsException.class, LockedAccountException.class, AuthenticationException.class). to("mock:authenticationException"); from("direct:secureEndpoint"). policy(securityPolicy). to("log:incoming payload"). to("mock:success"); } }; }
protected RouteBuilder createRouteBuilder() throws Exception { final ShiroSecurityPolicy securityPolicy = new ShiroSecurityPolicy("src/test/resources/securityconfig.ini", passPhrase); securityPolicy.setBase64(true); return new RouteBuilder() { @SuppressWarnings("unchecked") public void configure() { onException(UnknownAccountException.class, IncorrectCredentialsException.class, LockedAccountException.class, AuthenticationException.class). to("mock:authenticationException"); from("direct:secureEndpoint"). policy(securityPolicy). to("log:incoming payload"). to("mock:success"); } }; }
protected RouteBuilder createRouteBuilder() throws Exception { final ShiroSecurityPolicy securityPolicy = new ShiroSecurityPolicy("src/test/resources/securityconfig.ini", passPhrase); return new RouteBuilder() { @SuppressWarnings("unchecked") public void configure() { onException(UnknownAccountException.class, IncorrectCredentialsException.class, LockedAccountException.class, AuthenticationException.class). to("mock:authenticationException"); from("direct:secureEndpoint"). policy(securityPolicy). to("log:incoming payload"). to("mock:success"); } }; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String password = new String(upToken.getPassword()); String userId = upToken.getUsername(); // username == password try { if (userId.endsWith(password) && userManager.getUser(userId) != null) { return new SimpleAuthenticationInfo(new SimplePrincipalCollection(token.getPrincipal(), this.getName()), userId); } else { throw new IncorrectCredentialsException("User [" + userId + "] bad credentials."); } } catch (UserNotFoundException e) { throw new UnknownAccountException("User [" + userId + "] not found."); } }
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); }
/** * * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { final UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; final User user = this.accountService .findUserByUsername(token.getUsername()); if (user != null) { return new SimpleAuthenticationInfo( token.getUsername(), user.getPassword(), this.getName()); } throw new IncorrectCredentialsException("Invalid user or password"); }
/** * * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { final UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; final User user = this.accountService .findUserByUsername(token.getUsername()); if (user != null) { return new SimpleAuthenticationInfo( user, user.getPassword(), this.getName()); } throw new IncorrectCredentialsException("Invalid user or password"); }
@Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { RegToken rtoken = null; if ( token instanceof UsernamePasswordToken ) { UsernamePasswordToken uptoken = (UsernamePasswordToken) token; rtoken = new RegToken(uptoken.getUsername(), new String(uptoken.getPassword())); } else if (token instanceof RegToken) { rtoken = (RegToken)token; } else { throw new IncorrectCredentialsException(); } String id = (String)rtoken.getPrincipal(); SaltedAuthenticationInfo info = getUserStore().checkUser(id); return info; }
@Override public boolean login(LoginVo loginVo) { Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken( loginVo.getUsername(), SecurityUtil.encodeMd5(loginVo .getPassword())); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { return false; } catch (IncorrectCredentialsException ice) { return false; } catch (LockedAccountException lae) { return false; } catch (AuthenticationException ae) { return false; } return true; }
@Override public Map<String, Object> login(String userName, String password) { Map<String, Object> loginInfo = new HashMap<String, Object>(); Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(userName, password); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { return null; } catch (IncorrectCredentialsException ice) { return null; } catch (LockedAccountException lae) { return null; } catch (AuthenticationException ae) { return null; } loginInfo.put(WizardWebUtils.USER_NAME, userName); loginInfo.put(WizardWebUtils.ROLE_NAME, getRole(currentUser)); return loginInfo; }
/** * 查询获得用户信息 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); }
public void doPost(MCRServletJob job) throws Exception { String username = getParameter(job, "username"); String plainTextPassword = getParameter(job, "password"); User user = new User(); user.setUsername(username); registrate(user, plainTextPassword); UsernamePasswordToken token = new UsernamePasswordToken(username,plainTextPassword); org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject(); try { currentUser.login(token); LOGGER.info("User [" + currentUser.getPrincipal().toString() + "] logged in successfully."); currentUser.getSession().setAttribute("username", username); } catch (UnknownAccountException uae) { LOGGER.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { LOGGER.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { LOGGER.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } job.getResponse().sendRedirect(applicationName + "/start"); }
public boolean tryLogin(String username, String password, Boolean rememberMe) { org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject(); if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(rememberMe); try { currentUser.login(token); LOGGER.info("User [" + currentUser.getPrincipal().toString() + "] logged in successfully."); // save username in the session currentUser.getSession().setAttribute("username", username); return true; } catch (UnknownAccountException uae) { LOGGER.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { LOGGER.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { LOGGER.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } } else { return true; } return false; }
@RequestMapping(value = "/login", method = RequestMethod.POST) public String login(HttpServletRequest request) throws Exception{ String exceptionClassName = (String) request.getAttribute("shiroLoginFailure"); if(exceptionClassName!=null){ if(UnknownAccountException.class.getName().equals(exceptionClassName)) { throw new CustomException("用户名不存在!"); } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) { throw new CustomException("用户名或密码错误"); } else { throw new Exception(); } } return "login"; }
/** * 登陆 * @param u * @param session * @return */ @At @POST public Object login(@Param("..")User u, HttpSession session, HttpServletResponse response,HttpServletRequest request){ String msg = checkUser(u,false); if(msg!=null){ return Response.fail(msg); } // session.setAttribute("me", user.getId()); // session.setAttribute("username", user.getUsername()); // session.setAttribute("sessionId",session.getId()); UsernamePasswordToken token = new UsernamePasswordToken(u.getUsername(),u.getPwd()); Subject subject = SecurityUtils.getSubject(); try { subject.login(token);// } catch (UnknownAccountException e2){ return Response.fail("账户不存在!"); }catch ( IncorrectCredentialsException e1){ return Response.fail("密码错误!"); } User fetch = dao.fetch(User.class, Cnd.where(User.USERNAME, "=", u.getUsername())); if( SecurityUtils.getSubject().isAuthenticated()){ subject.getSession().setAttribute("me", fetch.getId()); subject.getSession().setAttribute("username", fetch.getUsername()); subject.getSession().setAttribute("sessionId", session.getId()); return Response.ok("登陆成功!"); }else{ return Response.fail("登录失败!"); } }
/** * 认证(登录时调用) */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); //查询用户信息 SysUserEntity user = sysUserDao.queryByUserName(username); //账号不存在 if(user == null) { throw new UnknownAccountException("账号或密码不正确"); } //密码错误 if(!password.equals(user.getPassword())) { throw new IncorrectCredentialsException("账号或密码不正确"); } //账号锁定 if(user.getStatus() == 0){ throw new LockedAccountException("账号已被锁定,请联系管理员"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); return info; }
@RequestMapping(value = "/login", method = RequestMethod.POST) @ExceptionForward("/shiro/login") public String login(HttpServletRequest request) { String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if (UnknownAccountException.class.getName().equals(exception)) { failed("Unknown account."); } else if (IncorrectCredentialsException.class.getName().equals(exception)) { failed("Incorrect password."); } else { LoggerHelper.error("unknown error : " + exception); failed("Unknown error."); } return "shiro_login"; }
/** * 认证(登录时调用) */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); //查询用户信息 SysUserEntity user = sysUserService.queryByUserName(username); //账号不存在 if(user == null) { throw new UnknownAccountException("账号或密码不正确"); } //密码错误 if(!password.equals(user.getPassword())) { throw new IncorrectCredentialsException("账号或密码不正确"); } //账号锁定 if(user.getStatus() == 0){ throw new LockedAccountException("账号已被锁定,请联系管理员"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); return info; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String errorClassName = (String)req.getAttribute("shiroLoginFailure"); if(UnknownAccountException.class.getName().equals(errorClassName)) { req.setAttribute("error", "用户名/密码错误"); } else if(IncorrectCredentialsException.class.getName().equals(errorClassName)) { req.setAttribute("error", "用户名/密码错误"); } else if(errorClassName != null) { req.setAttribute("error", "未知错误:" + errorClassName); } req.getRequestDispatcher("/WEB-INF/jsp/formfilterlogin.jsp").forward(req, resp); }
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); String password = new String((char[])token.getCredentials()); if(!"zhang".equals(username)){ //用户名错误 throw new UnknownAccountException(); } if(!"123".equals(password)){ //密码错误 throw new IncorrectCredentialsException(); } //认证成功 返回一个Authentication的实现 return new SimpleAuthenticationInfo(username + "@163.com", password, getName()); }