org.apache.shiro.authc.UnknownAccountException Java Examples

The following examples show how to use org.apache.shiro.authc.UnknownAccountException. 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: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #2
Source File: ShiroServiceImpl.java    From spring-boot-seed with MIT License 6 votes vote down vote up
/**
 * 校验用户密码
 *
 * @param user     用户
 * @param password 需要校验的密码
 */
private void validateUserPassword(User user, String password) {
    if (user == null) {
        // 用户不存在
        throw new UnknownAccountException();
    }
    if (BooleanEnum.NO.getValue() == user.getStateCode()) {
        // 账户不可用
        throw new LockedAccountException();
    }
    String passwordDb = user.getPassword();
    if (!passwordDb.equals(PasswordUtil.encrypt(password, user.getSalt()))) {
        //密码不正确
        throw new IncorrectCredentialsException();
    }
}
 
Example #3
Source File: LoginController.java    From SpringBootBucket with MIT License 6 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, Map<String, Object> map) {
    _logger.info("登录方法start.........");
    // 登录失败从request中获取shiro处理的异常信息。shiroLoginFailure:就是shiro异常类的全类名.
    Object exception = request.getAttribute("shiroLoginFailure");
    String msg;
    if (exception != null) {
        if (UnknownAccountException.class.isInstance(exception)) {
            msg = "用户名不正确,请重新输入";
        } else if (IncorrectCredentialsException.class.isInstance(exception)) {
            msg = "密码错误,请重新输入";
        } else if (IncorrectCaptchaException.class.isInstance(exception)) {
            msg = "验证码错误";
        } else if (ForbiddenUserException.class.isInstance(exception)) {
            msg = "该用户已被禁用,如有疑问请联系系统管理员。";
        } else {
            msg = "发生未知错误,请联系管理员。";
        }
        map.put("username", request.getParameter("username"));
        map.put("password", request.getParameter("password"));
        map.put("msg", msg);
        return "login";
    }
    //如果已经登录,直接跳转主页面
    return "index";
}
 
Example #4
Source File: GenericAuthorizingRealm.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Authenticates a user and retrieves its information.
 *
 * @param token
 *            the authentication token
 * @throws AuthenticationException
 *             if there is an error during authentication.
 */
@Override
protected IamAuthenticationInfo doAuthenticationInfo(GenericAuthenticationToken token) throws AuthenticationException {
	// Get account by loginId(user-name)
	IamPrincipalInfo info = configurer.getIamAccount(new SimpleParameter((String) token.getPrincipal()));
	log.debug("Get IamPrincipalInfo:{} by token:{}", info, token);

	// To authenticationInfo
	if (isNull(info) || isBlank(info.getPrincipal())) {
		throw new UnknownAccountException(bundle.getMessage("GeneralAuthorizingRealm.notAccount", token.getPrincipal()));
	}

	// Authenticate attributes.(roles/permissions/rememberMe)
	PrincipalCollection principals = createPermitPrincipalCollection(info);
	return new GenericAuthenticationInfo(info, principals, getName());
}
 
Example #5
Source File: CaptchaFormAuthenticationFilter.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #6
Source File: OrientDbRealm.java    From spring-boot-shiro-orientdb with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
        final AuthenticationToken token)
        throws AuthenticationException {
    final UsernamePasswordToken credentials = (UsernamePasswordToken) token;
    final String email = credentials.getUsername();
    if (email == null) {
        throw new UnknownAccountException("Email not provided");
    }
    final User user = userRepository.findByEmailAndActive(email, true);
    if (user == null) {
        throw new UnknownAccountException("Account does not exist");
    }
    return new SimpleAuthenticationInfo(email, user.getPassword().toCharArray(),
            ByteSource.Util.bytes(email), getName());
}
 
Example #7
Source File: OrientDbRealm.java    From spring-boot-shiro-orientdb with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
        final PrincipalCollection principals) {
    // retrieve role names and permission names
    final String email = (String) principals.getPrimaryPrincipal();
    final User user = userRepository.findByEmailAndActive(email, true);
    if (user == null) {
        throw new UnknownAccountException("Account does not exist");
    }
    final int totalRoles = user.getRoles().size();
    final Set<String> roleNames = new LinkedHashSet<>(totalRoles);
    final Set<String> permissionNames = new LinkedHashSet<>();
    if (totalRoles > 0) {
        for (Role role : user.getRoles()) {
            roleNames.add(role.getName());
            for (Permission permission : role.getPermissions()) {
                permissionNames.add(permission.getName());
            }
        }
    }
    final SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
    info.setStringPermissions(permissionNames);
    return info;
}
 
Example #8
Source File: JpaRealm.java    From init-spring with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
{
	String username = token.getPrincipal().toString();
	User user = this.jpaRealmRepository.findUserByName(username);

	if (null == user)
	{
		log.error("没有相关用户!");
		throw new UnknownAccountException();
	}

	String principal = username;
	String hashedCredentials = user.getPasswordHash();
	ByteSource credentialsSalt = ByteSource.Util.bytes(user.getName() + new String(user.getPasswordSalt()));
	String realmName = getName();

	SimpleAuthenticationInfo authentication = new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, realmName);
	return authentication;
}
 
Example #9
Source File: AdminAuthController.java    From mall with MIT License 6 votes vote down vote up
@PostMapping("/login")
public Object login(@RequestBody String body) {
    String username = JacksonUtil.parseString(body, "username");
    String password = JacksonUtil.parseString(body, "password");

    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        return ResponseUtil.badArgument();
    }

    Subject currentUser = SecurityUtils.getSubject();
    try {
        currentUser.login(new UsernamePasswordToken(username, password));
    } catch (UnknownAccountException uae) {
        return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号或密码不正确");
    } catch (LockedAccountException lae) {
        return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号已锁定不可用");

    } catch (AuthenticationException ae) {
        return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, ae.getMessage());
    }
    return ResponseUtil.ok(currentUser.getSession().getId());
}
 
Example #10
Source File: FormAuthenticationFilter.java    From frpMgr with MIT License 6 votes vote down vote up
/**
 * 登录失败调用事件
 */
@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 = Global.getText("sys.login.failure");
	} else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")) {
		message = StringUtils.replace(e.getMessage(), "msg:", "");
	} else {
		message = Global.getText("sys.login.error");
		logger.error(message, e); // 输出到日志文件
	}
	request.setAttribute(getFailureKeyAttribute(), className);
	request.setAttribute(DEFAULT_MESSAGE_PARAM, message);
	return true;
}
 
Example #11
Source File: HomeController.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/login")
public String login(HttpServletRequest request, Map<String, Object> map) throws Exception {
      // 登录失败从request中获取shiro处理的异常信息。
    // shiroLoginFailure:就是shiro异常类的全类名.
    //初始登陆用户名密码long/longzhonghua,或者long/123456
    String exception = (String) request.getAttribute("shiroLoginFailure");
    System.out.println("exception=" + exception);
    String msg = "";
    if (exception != null) {
        if (UnknownAccountException.class.getName().equals(exception)) {
                   msg = "账号不存在:";
        } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                     msg = "密码不正确:";
        } else if ("kaptchaValidateFailed".equals(exception)) {
                         msg = "验证码错误";
        } else {
            msg = "else >> " + exception;

        }
    }
    map.put("msg", msg);
    // 此方法不处理登录成功,由shiro进行处理
    return "/login";
}
 
Example #12
Source File: ExceptionUtils.java    From onedev with MIT License 6 votes vote down vote up
public static void handle(HttpServletResponse response, Exception exception) {
	try {
		if (ExceptionUtils.find(exception, UnauthenticatedException.class) != null) {
			requireAuthentication(response);
		} else if (find(exception, UnauthorizedException.class) != null) {
			if (!SecurityUtils.getSubject().isAuthenticated()) 
				requireAuthentication(response);
			else 
				response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied.");
		} else if (find(exception, IncorrectCredentialsException.class) != null) {
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Incorrect credentials.");
		} else if (find(exception, UnknownAccountException.class) != null) {
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unknown user name.");
		} else {
			logger.warn("Error serving request", exception);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage());
		} 
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #13
Source File: UserRealm.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
/**
 * 认证(登录时调用)
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
		throws AuthenticationException {
	UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
	// 查询用户信息
	SysUser sysUser = sysUserService.findByLoginName(token.getUsername());
	// 账号不存在
	if (sysUser == null) {
		throw new UnknownAccountException("账号或密码不正确");
	}
	// 禁用状态
	if (SysUser.STATUS_STOP.equals(sysUser.getStatus())) {
		throw new LockedAccountException("账号已被禁用");
	}
	User user = new User(sysUser.getId(), sysUser.getDeptId(), sysUser.getDeptName(), sysUser.getLoginName(),
			sysUser.getName(),sysUser.getStatus());
	//放入角色
	user.setRoles(sysRoleService.findByUserId(user.getUserId()));
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, sysUser.getPassword(),
			ByteSource.Util.bytes(sysUser.getSalt()), getName());
	return info;
}
 
Example #14
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #15
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #16
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #17
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #18
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 登录认证
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	String userName = (String) token.getPrincipal();
	String password = new String((char[]) token.getCredentials());

	System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
	User user = userMapper.findByUserName(userName);

	if (user == null) {
		throw new UnknownAccountException("用户名或密码错误!");
	}
	if (!password.equals(user.getPassword())) {
		throw new IncorrectCredentialsException("用户名或密码错误!");
	}
	if (user.getStatus().equals("0")) {
		throw new LockedAccountException("账号已被锁定,请联系管理员!");
	}
	SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
	return info;
}
 
Example #19
Source File: AccountController.java    From VideoMeeting with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #20
Source File: MyCustomRealm.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
  throws AuthenticationException {

    UsernamePasswordToken uToken = (UsernamePasswordToken) token;

    if(uToken.getUsername() == null
      || uToken.getUsername().isEmpty()
      || !credentials.containsKey(uToken.getUsername())
      ) {
        throw new UnknownAccountException("username not found!");
    }


    return new SimpleAuthenticationInfo(
      uToken.getUsername(), credentials.get(uToken.getUsername()),
      getName());
}
 
Example #21
Source File: DatabaseRealm.java    From java-platform with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	if (token instanceof UsernamePasswordToken) {
		String username = ((UsernamePasswordToken) token).getUsername();
		char[] password = ((UsernamePasswordToken) token).getPassword();

		if (Strings.isNullOrEmpty(username) || password == null) {
			return null;
		}

		User user = userRepository.findByUsername(username);
		if (user == null) {
			throw new UnknownAccountException();
		}

		return new SimpleAuthenticationInfo(new Principal(user.getId(), username), user.getPassword(), new SimpleByteSource(user.getUsername()),
				getName());
	}
	return null;
}
 
Example #22
Source File: DbRealm.java    From dpCms with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
        final AuthenticationToken token)
        throws AuthenticationException {
    final UsernamePasswordToken credentials = (UsernamePasswordToken) token;
    final String userName = credentials.getUsername();
    if (userName == null) {
        throw new UnknownAccountException("userName not provided");
    }
    Account account = accountRepository.findByLoginName(userName);
    if (account == null) {
        throw new UnknownAccountException("Account does not exist");
    }
    return new SimpleAuthenticationInfo(userName, account.getPassword().toCharArray(),
            ByteSource.Util.bytes(userName), getName());
}
 
Example #23
Source File: LoginController.java    From roncoo-pay with Apache License 2.0 6 votes vote down vote up
/**
 * 函数功能说明 : 进入后台登陆页面.
 *
 * @参数: @return
 * @return String
 * @throws
 */
@RequestMapping("/login")
public String login(HttpServletRequest req, Model model) {

	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 (PermissionException.class.getName().equals(exceptionClassName)) {
		error = "网络异常,请联系龙果管理员";
	} else if (exceptionClassName != null) {
		error = "错误提示:" + exceptionClassName;
	}
	model.addAttribute("message", error);
	return "system/login";
}
 
Example #24
Source File: SystemLoginController.java    From cms with Apache License 2.0 6 votes vote down vote up
@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 #25
Source File: LoginController.java    From cms with Apache License 2.0 6 votes vote down vote up
@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 #26
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 #27
Source File: LoginController.java    From mumu with Apache License 2.0 6 votes vote down vote up
@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";

}
 
Example #28
Source File: FormAuthenticationFilter.java    From easyweb with Apache License 2.0 6 votes vote down vote up
/**
 * 登录失败调用事件
 */
@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;
}
 
Example #29
Source File: ApiServiceImpl.java    From wangmarket with Apache License 2.0 6 votes vote down vote up
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 #30
Source File: MyShiroRealm.java    From EasyReport with Apache License 2.0 6 votes vote down vote up
@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());
}