Java 类org.apache.shiro.authc.LockedAccountException 实例源码

项目:JavaQuarkBBS    文件:PageController.java   
/**
 * 用户登录
 * @param request
 * @param user
 * @param model
 * @return
 */
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(HttpServletRequest request, AdminUser user, Model model) {

    if (StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){
        request.setAttribute("msg","用户名或者密码不能为空!");
        return "login";
    }
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
    try {
        subject.login(token);
        return "redirect:/initPage";
    }catch (LockedAccountException lae) {
        token.clear();
        request.setAttribute("msg", "用户已经被锁定不能登录,请与管理员联系!");
        return "login";
    } catch (AuthenticationException e) {
        token.clear();
        request.setAttribute("msg", "用户或密码不正确!");
        return "login";
    }
}
项目:LazyAdmin    文件:AuthController.java   
@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";
}
项目:xproject    文件:AdminUserRealm.java   
/**
 * 用户认证-验证用户是否登录、用户名密码是否匹配
 */
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    logger.info(">>> 【用户认证】token = {}", token);
    String userName = (String)token.getPrincipal();
    AdminUser user = getPrincipalService().getPrincipalObject(userName);
       if(user == null) {
           throw new UnknownAccountException("Unknown account: " + userName);//没找到帐号
       }
       if(AdminUserStatusEnum.ADMIN_USER_STATUS_DISABLED.getStatusCode().equals(user.getStatus())) {
           throw new LockedAccountException("Account[" + userName + "] has been locked!"); //帐号锁定
       }
       //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
       SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
               user.getUserName(), //用户名
               user.getPassword(), //密码
               ByteSource.Util.bytes(user.getPasswordSalt()),//salt
               getName()  //realm name
       );
       return authenticationInfo;
}
项目:bibliometrics    文件:BibliometricReportRetrievalServlet.java   
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;
}
项目:bibliometrics    文件:BibliometricReportDisplayServlet.java   
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;
}
项目:CMSdemo    文件:HomeController.java   
@PostMapping("/login")
public String login(HttpServletRequest request, User user, Model model){
    if (StringUtils.isEmpty(user.getLoginId()) || StringUtils.isEmpty(user.getPassword())) {
        request.setAttribute("msg", "用户名或密码不能为空!");
        return "login";
    }
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token=new UsernamePasswordToken(user.getLoginId(),user.getPassword());
    try {
        subject.login(token);
        return "manage";
    }catch (LockedAccountException lae) {
        token.clear();
        request.setAttribute("msg", "用户已经被锁定不能登录,请与管理员联系!");
        return "login";
    } catch (AuthenticationException e) {
        token.clear();
        request.setAttribute("msg", "用户或密码不正确!");
        return "login";
    }
}
项目:PowerApi    文件:AuthController.java   
@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";
}
项目:PowerApi    文件:DashboardController.java   
@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";
    }
}
项目:mblog    文件:CallbackController.java   
/**
 * 执行登录请求
 *
 * @param username
 * @param request
 * @return
 */
private String login(String username, String accessToken, HttpServletRequest request) {
    String ret = getView(Views.LOGIN);

    if (StringUtils.isNotBlank(username)) {
        AuthenticationToken token = createToken(username, accessToken);

        try {
            SecurityUtils.getSubject().login(token);

            ret = Views.REDIRECT_HOME;
        } catch (AuthenticationException e) {
            logger.error(e);
            if (e instanceof UnknownAccountException) {
                throw new MtonsException("用户不存在");
            } else if (e instanceof LockedAccountException) {
                throw new MtonsException("用户被禁用");
            } else {
                throw new MtonsException("用户认证失败");
            }
        }
        return ret;
    }
    throw new MtonsException("登录失败!");
}
项目:windows-file-change    文件:NutDaoRealm.java   
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
      UsernamePasswordToken upToken = (UsernamePasswordToken) token;

     /* if (Strings.isBlank(upToken.getCaptcha()))
          throw new AuthenticationException("验证码不能为空");
      String _captcha = Strings.sBlank(SecurityUtils.getSubject().getSession(true).getAttribute(Toolkit.captcha_attr));
      if (!upToken.getCaptcha().equalsIgnoreCase(_captcha))
          throw new AuthenticationException("验证码错误");*/

      User user = dao().fetch(User.class, Cnd.where("name", "=", upToken.getUsername()));
      if (user == null)
          return null;
      if (user.isLocked()) 
          throw new LockedAccountException("Account [" + upToken.getUsername() + "] is locked.");
      ByteSource salt = ByteSource.Util.bytes(user.getSalt());
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
info.setCredentialsSalt(salt);
return info;
  }
项目:dms-webapp    文件:UserRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    String username = (String)token.getPrincipal();

    SysUsers user = userService.findByUsername(username);

    if(user == null) {
        throw new UnknownAccountException();//没找到帐号
    }

    if(Boolean.TRUE.equals(user.getLocked())) {
        throw new LockedAccountException(); //帐号锁定
    }

    //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
            username, //用户名
            user.getPassword(), //密码
            ByteSource.Util.bytes(user.getSalt()),//salt=salt
            getName()  //realm name
    );
    return authenticationInfo;
}
项目:Camel    文件:ShiroAuthenticationReauthenticateFalseAndNewUserTest.java   
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");
        }
    };
}
项目:Camel    文件:ShiroAuthenticationBase64Test.java   
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");
        }
    };
}
项目:Camel    文件:ShiroAuthenticationTest.java   
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");
        }
    };
}
项目:MultimediaDesktop    文件:CaptchaFormAuthenticationFilter.java   
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);
}
项目:jee-restful-web    文件:UserRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    String username = (String) token.getPrincipal();

    User user = userService.findByName(username);

    if (user == null) {
        throw new UnknownAccountException();// 没找到帐号
    }

    if (Boolean.TRUE.equals(user.getLocked())) {
        throw new LockedAccountException(); // 帐号锁定
    }

    // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得不好可以自定义实现
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), // 密码
            ByteSource.Util.bytes(user.getSalt()),// salt
            getName() // realm name
    );
    return authenticationInfo;
}
项目:maker    文件:OperatorRealm.java   
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
        throws AuthenticationException {
    Object _principal = token.getPrincipal();
    final String username = ((String) _principal);
    final Operator operator =  commonRepository.findOne("t_operator", "username", username, new OperatorRowMapper());
    boolean _equals = Objects.equal(operator, null);
    if (_equals) {
        throw new UnknownAccountException();
    }
    Boolean _enable = operator.getEnable();
    boolean _equals_1 = Boolean.FALSE.equals(_enable);
    if (_equals_1) {
        throw new LockedAccountException();
    }
    String _username = operator.getUsername();
    String _password = operator.getPassword();
    byte[] _bytes = "I\'m a salt".getBytes();
    ByteSource _bytes_1 = ByteSource.Util.bytes(_bytes);
    String _name = this.getName();
    final SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(_username, _password,
            _bytes_1, _name);
    return authenticationInfo;
}
项目:EasyReport    文件:MyShiroRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
    throws AuthenticationException {
    final String account = (String)token.getPrincipal();
    final User user = this.membershipFacade.getUser(account);

    if (user == null) {
        throw new UnknownAccountException();
    }
    if (user.getStatus() == 0) {
        throw new LockedAccountException();
    }

    // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
    return new SimpleAuthenticationInfo(
        user.getAccount(), user.getPassword(),
        ByteSource.Util.bytes(user.getCredentialsSalt()),
        getName());
}
项目:kha    文件:KhaRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;

    SimpleAccount account = getAccountFromUsername(upToken.getUsername());

    if (account != null) {
        if (account.isLocked()) {
            throw new LockedAccountException("Account [" + account + "] is locked.");
        }
        if (account.isCredentialsExpired()) {
            String msg = "The credentials for account [" + account + "] are expired";
            throw new ExpiredCredentialsException(msg);
        }
    }

    return account;
}
项目:mix-web    文件:MixRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    try {
        String userName = (String) token.getPrincipal();

        User user = userService.getUserByUserName(userName);

        if (null == user) {
            throw new UnknownAccountException();
        }

        if(MixConstants.USER_STATUS_LOCKED.equals(user.getUserStatus())) {
            throw new LockedAccountException();
        }

        return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), 
                ByteSource.Util.bytes(user.getCredentialsSalt()), getName());
    } catch (Exception e) {
         throw null;
    }
}
项目:wizard    文件:LoginServiceImpl.java   
@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;
}
项目:wizard    文件:LoginServiceImpl.java   
@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;
}
项目:wizard    文件:LoginServiceImpl.java   
@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;
}
项目:wizard    文件:LoginServiceImpl.java   
@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;
}
项目:wizard    文件:LoginServiceImpl.java   
@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;
}
项目:Grapi    文件:OAuth2Realm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
    OAuth2Token token = (OAuth2Token) authToken;

    SimpleAccount account = authorizationServer.getAccountFromAccessToken(token.getToken());

    if (account != null) {
        if (account.isLocked()) {
            throw new LockedAccountException("Account [" + account + "] is locked.");
        }
        if (account.isCredentialsExpired()) {
            String msg = "The credentials for account [" + account + "] are expired";
            throw new ExpiredCredentialsException(msg);
        }
    }

    return account;
}
项目:spring_mybatis_shiro    文件:UserAuthorizingRealm.java   
/**
 * 查询获得用户信息 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();
}
项目:bibliometrics    文件:UserRegistrationServlet.java   
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");
}
项目:bibliometrics    文件:UserLoggingServlet.java   
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;
}
项目:tianti    文件:ShiroDBRealm.java   
/**
 * 验证当前用户
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken)authcToken;

       if(StringUtils.isEmpty(token.getUsername())){
        return null;
       }

       User user = userService.findUserByName(token.getUsername());
       if(user != null){

        if(user.getStatus() == User.STATUS_NO){
            throw new LockedAccountException();
        }

        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());

        setSession(WebHelper.SESSION_LOGIN_USER, user);

        initMenu(user.getId());

        return authcInfo;
       }

       return null;
}
项目:renren-msg    文件:UserRealm.java   
/**
 * 认证(登录时调用)
 */
@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;
}
项目:renren-security    文件:UserRealm.java   
/**
 * 认证(登录时调用)
 */
@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;
}
项目:mblog    文件:SidebarController.java   
@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody Data login(String username, String password, ModelMap model) {
    Data data = Data.failure("操作失败");

    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
        return data;
    }

    AuthenticationToken token = createToken(username, password);
    if (token == null) {
        data.setMessage("用户名或密码错误");
        return data;
    }

    try {
        SecurityUtils.getSubject().login(token);
        data = Data.success("登录成功", getSubject().getProfile());

    } catch (AuthenticationException e) {
        if (e instanceof UnknownAccountException) {
            data.setMessage("用户不存在");
        } else if (e instanceof LockedAccountException) {
            data.setMessage("用户被禁用");
        } else {
            data.setMessage("用户认证失败");
        }
    }
    return data;
}
项目:mblog    文件:AccountRealm.java   
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    AccountProfile profile = getAccount(userService, token);

    if(profile.getStatus() == Const.STATUS_CLOSED){
        throw new LockedAccountException(profile.getName());
    }

    AccountAuthenticationInfo info = new AccountAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
    info.setProfile(profile);

    return info;
}
项目:pairing-shiro-javaee7    文件:ShiroExceptionMapper.java   
@Override
public Response toResponse(Exception ex) {

    if (ex instanceof UnknownAccountException) {
        return Response.status(Response.Status.FORBIDDEN)
                .header(ShiroExceptionMapper.CAUSE, "Your username wrong")
                .type(MediaType.TEXT_HTML)
                .build();
    }
    if (ex instanceof IncorrectCredentialsException) {
        return Response.status(Response.Status.UNAUTHORIZED)
                .header(ShiroExceptionMapper.CAUSE, "Password is incorrect")
                .type(MediaType.TEXT_HTML)
                .build();
    }
    if (ex instanceof LockedAccountException) {
        return Response.status(Response.Status.CONFLICT)
                .header(ShiroExceptionMapper.CAUSE, "This username is locked")
                .type(MediaType.TEXT_HTML)
                .build();
    }
    if (ex instanceof AuthenticationException) {
        return Response.status(Response.Status.BAD_REQUEST)
                .header(ShiroExceptionMapper.CAUSE, ex.getMessage())
                .type(MediaType.TEXT_HTML)
                .build();
    }

    return Response.serverError().
            header(ShiroExceptionMapper.CAUSE, ex.toString()).build();
}
项目:java-platform    文件:AjaxAuthenticationFilter.java   
@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);
}
项目:Camel    文件:ShiroSecurityProcessor.java   
private void authenticateUser(Subject currentUser, ShiroSecurityToken securityToken) {
    boolean authenticated = currentUser.isAuthenticated();
    boolean sameUser = securityToken.getUsername().equals(currentUser.getPrincipal());
    LOG.trace("Authenticated: {}, same Username: {}", authenticated, sameUser);

    if (!authenticated || !sameUser) {
        UsernamePasswordToken token = new UsernamePasswordToken(securityToken.getUsername(), securityToken.getPassword());
        if (policy.isAlwaysReauthenticate()) {
            token.setRememberMe(false);
        } else {
            token.setRememberMe(true);
        }

        try {
            currentUser.login(token);
            LOG.debug("Current user {} successfully authenticated", currentUser.getPrincipal());
        } catch (UnknownAccountException uae) {
            throw new UnknownAccountException("Authentication Failed. There is no user with username of " + token.getPrincipal(), uae.getCause());
        } catch (IncorrectCredentialsException ice) {
            throw new IncorrectCredentialsException("Authentication Failed. Password for account " + token.getPrincipal() + " was incorrect!", ice.getCause());
        } catch (LockedAccountException lae) {
            throw new LockedAccountException("Authentication Failed. The account for username " + token.getPrincipal() + " is locked."
                    + "Please contact your administrator to unlock it.", lae.getCause());
        } catch (AuthenticationException ae) {
            throw new AuthenticationException("Authentication Failed.", ae.getCause());
        }
    }
}
项目:EasyEE    文件:AuthenticationInterceptor.java   
@Override
    public void afterSuccess(ServletRequest request, ServletResponse response, AuthenticationToken token)
            throws Exception {
        Subject subject = SecurityUtils.getSubject();
        // 不要强制转换,防止 devtools 的 RestartClassLoader 导致的 cast exception
        UsernamePasswordEncodeToken downToken = new UsernamePasswordEncodeToken();
        downToken.setUserId(Integer.valueOf(token.getClass().getMethod("getUserId").invoke(token).toString()));
        downToken.setName(token.getClass().getMethod("getName").invoke(token).toString());
        downToken.setPassword((char[])token.getClass().getMethod("getPassword").invoke(token));
        downToken.setRealName(token.getClass().getMethod("getRealName").invoke(token).toString());
        downToken.setStatus(Integer.valueOf(token.getClass().getMethod("getStatus").invoke(token).toString()));
        // 用户锁定
        if (downToken.getStatus() == SysUser.STATUS_LOCK) {
            subject.logout();
            throw new LockedAccountException("账户已锁定!");
        }

        // 存入用户信息到Session
        // SysUser sysUser=new SysUser(downToken.getName(), new
        // String(downToken.getPassword()));
        SysUser sysUser = new SysUser(downToken.getName(), "");
        sysUser.setPassword(new String(downToken.getPassword()));
        sysUser.setRealName(downToken.getRealName());
        sysUser.setStatus(downToken.getStatus());
        sysUser.setUserId(downToken.getUserId());

        subject.getSession().setAttribute("USER", sysUser);

        // 初始化菜单列表
        initMenu(subject.getSession(), downToken);

//      System.out.println("登录成功!");
//      System.out.println(sysOperationPermissionService.getAllOpreationNames());

        // 保存所有权限对应的权限名称,权限备注
        subject.getSession().setAttribute("operationsName", sysOperationPermissionService.getAllOpreationNames());
    }
项目:EasyEE    文件:AuthenticationInterceptor.java   
@Override
    public void afterSuccess(ServletRequest request, ServletResponse response, AuthenticationToken token)
            throws Exception {
        Subject subject = SecurityUtils.getSubject();
        // 不要强制转换,防止 devtools 的 RestartClassLoader 导致的 cast exception
        UsernamePasswordEncodeToken downToken = new UsernamePasswordEncodeToken();
        downToken.setUserId(Integer.valueOf(token.getClass().getMethod("getUserId").invoke(token).toString()));
        downToken.setName(token.getClass().getMethod("getName").invoke(token).toString());
        downToken.setPassword((char[])token.getClass().getMethod("getPassword").invoke(token));
        downToken.setRealName(token.getClass().getMethod("getRealName").invoke(token).toString());
        downToken.setStatus(Integer.valueOf(token.getClass().getMethod("getStatus").invoke(token).toString()));
        // 用户锁定
        if (downToken.getStatus() == SysUser.STATUS_LOCK) {
            subject.logout();
            throw new LockedAccountException("账户已锁定!");
        }

        // 存入用户信息到Session
        // SysUser sysUser=new SysUser(downToken.getName(), new
        // String(downToken.getPassword()));
        SysUser sysUser = new SysUser(downToken.getName(), "");
        sysUser.setPassword(new String(downToken.getPassword()));
        sysUser.setRealName(downToken.getRealName());
        sysUser.setStatus(downToken.getStatus());
        sysUser.setUserId(downToken.getUserId());

        subject.getSession().setAttribute("USER", sysUser);

        // 初始化菜单列表
        initMenu(subject.getSession(), downToken);

//      System.out.println("登录成功!");
//      System.out.println(sysOperationPermissionService.getAllOpreationNames());

        // 保存所有权限对应的权限名称,权限备注
        subject.getSession().setAttribute("operationsName", sysOperationPermissionService.getAllOpreationNames());
    }
项目:EasyEE    文件:AuthenticationInterceptor.java   
@Override
    public void afterSuccess(ServletRequest request, ServletResponse response, AuthenticationToken token)
            throws Exception {
        Subject subject = SecurityUtils.getSubject();
        // 不要强制转换,防止 devtools 的 RestartClassLoader 导致的 cast exception
        UsernamePasswordEncodeToken downToken = new UsernamePasswordEncodeToken();
        downToken.setUserId(Integer.valueOf(token.getClass().getMethod("getUserId").invoke(token).toString()));
        downToken.setName(token.getClass().getMethod("getName").invoke(token).toString());
        downToken.setPassword((char[])token.getClass().getMethod("getPassword").invoke(token));
        downToken.setRealName(token.getClass().getMethod("getRealName").invoke(token).toString());
        downToken.setStatus(Integer.valueOf(token.getClass().getMethod("getStatus").invoke(token).toString()));
        // 用户锁定
        if (downToken.getStatus() == SysUser.STATUS_LOCK) {
            subject.logout();
            throw new LockedAccountException("账户已锁定!");
        }

        // 存入用户信息到Session
        // SysUser sysUser=new SysUser(downToken.getName(), new
        // String(downToken.getPassword()));
        SysUser sysUser = new SysUser(downToken.getName(), "");
        sysUser.setPassword(new String(downToken.getPassword()));
        sysUser.setRealName(downToken.getRealName());
        sysUser.setStatus(downToken.getStatus());
        sysUser.setUserId(downToken.getUserId());

        subject.getSession().setAttribute("USER", sysUser);

        // 初始化菜单列表
        initMenu(subject.getSession(), downToken);

//      System.out.println("登录成功!");
//      System.out.println(sysOperationPermissionService.getAllOpreationNames());

        // 保存所有权限对应的权限名称,权限备注
        subject.getSession().setAttribute("operationsName", sysOperationPermissionService.getAllOpreationNames());
    }