org.apache.shiro.authc.AccountException Java Examples

The following examples show how to use org.apache.shiro.authc.AccountException. 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: ShiroExceptionHandler.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Response toResponse(ShiroException exception) {

    Status status = Status.FORBIDDEN; // Invalid api key
    if (exception instanceof AccountException) {
        // API key missing
        status = Status.BAD_REQUEST;
        logger.warn(exception.getMessage());
    } else if (exception instanceof AuthorizationException) {
        // Not enough permissions
        status = Status.UNAUTHORIZED;
        logger.warn(exception.getMessage());
    } else {
        logger.error(exception.getMessage(), exception);
    }
    return Response.status(status).type(MediaType.APPLICATION_JSON)
            .entity(ErrorEntity.with().message(exception.getMessage()).build()).build();
}
 
Example #2
Source File: JdbcAuthenticationRealm.java    From base-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 用户登录的身份验证方法
 * 
 */
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

       String username = usernamePasswordToken.getUsername();
       
       if (username == null) {
           throw new AccountException("用户名不能为空");
       }
       
       User user = accountManager.getUserByUsername(username);
       
       if (user == null) {
           throw new UnknownAccountException("用户不存在");
       }
       
       if (user.getState().equals(State.Disable.getValue())) {
       	 throw new DisabledAccountException("你的账户已被禁用,请联系管理员开通.");
       }
       
       SessionVariable model = new SessionVariable(user);
       
       return new SimpleAuthenticationInfo(model,user.getPassword(),getName());
}
 
Example #3
Source File: AdminAuthorizingRealm.java    From dts-shop with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

	UsernamePasswordToken upToken = (UsernamePasswordToken) token;
	String username = upToken.getUsername();
	String password = new String(upToken.getPassword());

	if (StringUtils.isEmpty(username)) {
		throw new AccountException("用户名不能为空");
	}
	if (StringUtils.isEmpty(password)) {
		throw new AccountException("密码不能为空");
	}

	List<DtsAdmin> adminList = adminService.findAdmin(username);
	Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
	if (adminList.size() == 0) {
		logger.error("找不到用户(" + username + ")的帐号信息");
		throw new UnknownAccountException("找不到用户(" + username + ")的帐号信息");
	}
	DtsAdmin admin = adminList.get(0);

	BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
	if (!encoder.matches(password, admin.getPassword())) {
		logger.error("找不到用户(" + username + ")的帐号信息");
		throw new UnknownAccountException("找不到用户(" + username + ")的帐号信息");
	}

	return new SimpleAuthenticationInfo(admin, password, getName());
}
 
Example #4
Source File: GenericCredentialsHashedMatcher.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public boolean doMatching(IamAuthenticationToken token, AuthenticationInfo info, List<String> factors) {
	GenericAuthenticationToken tk = (GenericAuthenticationToken) token;
	// Before preCheck.
	if (!coprocessor.preAuthenticatingAllowed(tk, info)) {
		throw new AccountException(bundle.getMessage("ServerSecurityCoprocessor.accessDenied", tk.getPrincipal()));
	}

	// Matching credentials.
	CredentialsToken credentialsToken = new CredentialsToken((String) tk.getPrincipal(), (String) tk.getCredentials(),
			tk.getSecureAlgKind());
	return securer.validate(credentialsToken, info);
}
 
Example #5
Source File: ExceptionHandleController.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Shiro权限认证异常
 *
 * @param e
 * @return
 */
@ExceptionHandler(value = {UnauthorizedException.class, AccountException.class})
@ResponseBody
public ResponseVO unauthorizedExceptionHandle(Throwable e) {
    e.printStackTrace(); // 打印异常栈
    return ResultUtil.error(HttpStatus.UNAUTHORIZED.value(), e.getLocalizedMessage());
}
 
Example #6
Source File: AjaxAuthenticationFilter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #7
Source File: AuthenticatingRealmImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) {
  UsernamePasswordToken upToken = (UsernamePasswordToken) token;

  CUser user;
  try {
    user = configuration.readUser(upToken.getUsername());
  }
  catch (UserNotFoundException e) {
    throw new UnknownAccountException("User '" + upToken.getUsername() + "' cannot be retrieved.", e);
  }

  if (user.getPassword() == null) {
    throw new CredentialsException("User '" + upToken.getUsername() + "' has no password, cannot authenticate.");
  }

  if (user.isActive()) {
    // Check for legacy user that has unsalted password hash
    // Update if unsalted password hash and valid credentials were specified
    if (hasLegacyPassword(user) && isValidCredentials(upToken, user)) {
      reHashPassword(user, new String(upToken.getPassword()));
    }

    return createAuthenticationInfo(user);
  }
  else if (CUser.STATUS_DISABLED.equals(user.getStatus())) {
    throw new DisabledAccountException("User '" + upToken.getUsername() + "' is disabled.");
  }
  else {
    throw new AccountException(
        "User '" + upToken.getUsername() + "' is in illegal status '" + user.getStatus() + "'.");
  }
}
 
Example #8
Source File: ZeppelinHubRealm.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken)
        throws AuthenticationException {
  UsernamePasswordToken token = (UsernamePasswordToken) authToken;
  if (StringUtils.isBlank(token.getUsername())) {
    throw new AccountException("Empty usernames are not allowed by this realm.");
  }
  String loginPayload = createLoginPayload(token.getUsername(), token.getPassword());
  User user = authenticateUser(loginPayload);
  LOG.debug("{} successfully login via ZeppelinHub", user.login);
  return new SimpleAuthenticationInfo(user.login, token.getPassword(), name);
}
 
Example #9
Source File: CaptchaAuthenticationFilter.java    From base-framework with Apache License 2.0 5 votes vote down vote up
/**
    * 重写父类方法,在shiro执行登录时先对比验证码,正确后在登录,否则直接登录失败
    */
@Override
protected boolean executeLogin(ServletRequest request,ServletResponse response) throws Exception {
	
	Session session = getSubject(request, response).getSession();
	//获取登录次数
	Integer number = (Integer) session.getAttribute(getLoginNumKeyAttribute());
	
	//首次登录,将该数量记录在session中
	if (number == null) {
		number = new Integer(1);
		session.setAttribute(getLoginNumKeyAttribute(), number);
	}
	
	//如果登录次数大于allowLoginNum,需要判断验证码是否一致
	if (number > getAllowLoginNum()) {
		//获取当前验证码
		String currentCaptcha = (String) session.getAttribute(getSessionCaptchaKeyAttribute());
		//获取用户输入的验证码
		String submitCaptcha = getCaptcha(request);
		//如果验证码不匹配,登录失败
		if (StringUtils.isEmpty(submitCaptcha) || !StringUtils.equals(currentCaptcha,submitCaptcha.toLowerCase())) {
			return onLoginFailure(this.createToken(request, response), new AccountException("验证码不正确"), request, response);
		}
	
	}
	
	return super.executeLogin(request, response);
}
 
Example #10
Source File: RetryLimitCredentialsMatcher.java    From springboot-learn with MIT License 4 votes vote down vote up
@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 #11
Source File: RetryLimitCredentialsMatcher.java    From springboot-shiro with MIT License 4 votes vote down vote up
@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;
}
 
Example #12
Source File: RetryLimitCredentialsMatcher.java    From OneBlog with GNU General Public License v3.0 4 votes vote down vote up
@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 #13
Source File: UserRealm.java    From MultimediaDesktop with Apache License 2.0 4 votes vote down vote up
/**
 * 认证回调函数,登录时调用.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
		AuthenticationToken authcToken) throws AuthenticationException {

	SystemLoginToken token = (SystemLoginToken) authcToken;

	if (token.getUsername() == null) {
		throw new AccountException("提交表单未包含用户名.");
	}

	// 增加判断验证码逻辑
	String captcha = token.getCaptcha();
	String exitCode = (String) SecurityUtils
			.getSubject()
			.getSession()
			.getAttribute(
					com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
	if (null == captcha || !captcha.equalsIgnoreCase(exitCode)) {
		throw new ValidateCodeException("验证码错误");
	}

	UserLoginDto user = userservice.login(token.getUsername());

	if (user == null) {
		return null;
	}

	log.info("[用户登录]-[获取登录用户信息]-返回数据结果:"
			+ ToStringBuilder.reflectionToString(user));

	if (user != null && UserConstant.SUCCESS == user.getResult()) {

		// 用户没有被验证
		if (!user.isvStatus()) {
			log.info("用户没有通过邮箱验证.");
			throw new UnValidationAccountException();
		}
		
		if(user.isDisable()&&UserDisableReason.登录超过限制.equals(user.getDisableReason())){
			throw new LockedAccountException();
		}

		// 用户被锁定
		if (user.isDisable()) {
			log.info("用户被禁止登录.");
			throw new DisabledAccountException();
		}

		byte[] salt = Encodes.decodeHex(user.getSalt());

		return new SimpleAuthenticationInfo(new ShiroUser(user.getId(),
				user.getName(), user.getRole()), user.getPassword(),
				ByteSource.Util.bytes(salt), getName());
	}
	throw new UnknownAccountException();
}
 
Example #14
Source File: MyBatisRealm.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    String username = upToken.getUsername();

    // Null username is invalid
    if (username == null) {
        throw new AccountException("Null usernames are not allowed by this realm.");
    }

    SqlSession sqlSession = null;
    Connection conn = null;
    SimpleAuthenticationInfo info = null;
    try {
    	if(sqlSessionManager == null) {
    		sqlSessionManager = GlobalSqlSession.get(dataSourceName);
    	}
    	
        conn = (sqlSession = sqlSessionManager.openSession()).getConnection();
        String password = null;
        String salt = null;
        switch (saltStyle) {
        case NO_SALT:
            password = getPasswordForUser(conn, username)[0];
            break;
        case CRYPT:
            // TODO: separate password and hash from getPasswordForUser[0]
            throw new ConfigurationException("Not implemented yet");
            //break;
        case COLUMN:
            String[] queryResults = getPasswordForUser(conn, username);
            password = queryResults[0];
            salt = queryResults[1];
            break;
        case EXTERNAL:
            password = getPasswordForUser(conn, username)[0];
            salt = getSaltForUser(username);
        }

        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + ']');
        }

        info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
        
        if (salt != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }

    } catch (SQLException e) {
        final String message = "There was a SQL error while authenticating user [" + username + ']';
    	LOGGER.error(message, e);

        // Rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    } finally {
        if(sqlSession != null) {
            sqlSession.close();
        }
    }

    return info;
}
 
Example #15
Source File: LoginShiroFilter.java    From gazpachoquest with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    
    String method = requestContext.getMethod();
    String path = uriInfo.getPath();
    String query = uriInfo.getRequestUri().getQuery();
    logger.debug("New access to resource {}", path);
    if (path.startsWith("auth") || path.contains("api-docs")) {
        // Ignore the AuthenticationResource
        return;
    }

    Subject subject = SecurityUtils.getSubject();
   
    String dateUTC = requestContext.getHeaderString(HttpHeaders.DATE);
    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    if (authorizationHeader == null) {
        throw new AccountException("Hmac-SHA1 Authorization token is required");
    }
    String[] values = authorizationHeader.split(" ");
    String apiKeyAndSignature[] = StringUtils.split(values[1], ":");

    StringBuilder signedContent = new StringBuilder().append(method).append(" /").append(path);
    if (query != null) {
        signedContent.append("?").append(query);
    }

    if (dateUTC != null) {
        signedContent.append("\n").append(dateUTC);
    }
    /*-
    if ("POST".equals(method)) {
        DelegatingInputStream input = message.getContent(DelegatingInputStream.class);
        if (input != null) {
            input.cacheInput();
            try {
                signedContent.append("\n").append(IOUtils.toString(input));
            } catch (IOException e) {
                throw new IllegalStateException("Errors when reading POST content", e);
            }
        }
    }*/
    String apiKey = apiKeyAndSignature[0];
    String signature = apiKeyAndSignature[1];
    AuthenticationToken token = new HmacAuthToken.Builder().apiKey(apiKey).message(signedContent.toString())
            .signature(signature).dateUTC(dateUTC).build();
    subject.login(token); //
}
 
Example #16
Source File: ServerSecurityCoprocessor.java    From super-cloudops with Apache License 2.0 2 votes vote down vote up
/**
 * Preprocessing whether the generic authenticating check match is allowed.
 *
 * @param token
 * @param info
 * @return
 */
default boolean preAuthenticatingAllowed(IamAuthenticationToken token, AuthenticationInfo info) throws AccountException {
	return true;
}