org.apache.shiro.authc.LockedAccountException Java Examples

The following examples show how to use org.apache.shiro.authc.LockedAccountException. 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: OAuth2Realm.java    From kitty with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 认证(登录时调用)
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    String token = (String) authenticationToken.getPrincipal();
    // 根据accessToken,查询用户token信息
    SysUserToken sysUserToken = sysUserTokenService.findByToken(token);
    if(sysUserToken == null || sysUserToken.getExpireTime().getTime() < System.currentTimeMillis()){
    	// token已经失效
        throw new IncorrectCredentialsException("token失效,请重新登录");
    }
    // 查询用户信息
    SysUser user = sysUserService.findById(sysUserToken.getUserId());
    // 账号被锁定
    if(user.getStatus() == 0){
        throw new LockedAccountException("账号已被锁定,请联系管理员");
    }
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, token, getName());
    return info;
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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());
}
 
Example #7
Source File: PageController.java    From JavaQuarkBBS with Apache License 2.0 6 votes vote down vote up
/**
 * 用户登录
 * @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";
    }
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #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: 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 #17
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 #18
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 #19
Source File: AdminAuthController.java    From dts-shop with GNU Lesser General Public License v3.0 5 votes vote down vote up
@PostMapping("/login")
public Object login(@RequestBody String body) {
	logger.info("【请求开始】系统管理->用户登录,请求参数:body:{}", 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) {
		logger.error("系统管理->用户登录  错误:{}", AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD.desc());
		return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
	} catch (LockedAccountException lae) {
		logger.error("系统管理->用户登录 错误:{}", AdminResponseCode.ADMIN_LOCK_ACCOUNT.desc());
		return AdminResponseUtil.fail(AdminResponseCode.ADMIN_LOCK_ACCOUNT);

	} catch (AuthenticationException ae) {
		logger.error("系统管理->用户登录 错误:{}", AdminResponseCode.ADMIN_LOCK_ACCOUNT.desc());
		return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
	}

	logger.info("【请求结束】系统管理->用户登录,响应结果:{}", JSONObject.toJSONString(currentUser.getSession().getId()));
	return ResponseUtil.ok(currentUser.getSession().getId());
}
 
Example #20
Source File: MainController.java    From jboot-admin with Apache License 2.0 5 votes vote down vote up
@Before( {POST.class, LoginValidator.class} )
public void postLogin() {
    String loginName = getPara("loginName");
    String pwd = getPara("password");

    MuitiLoginToken token = new MuitiLoginToken(loginName, pwd);
    Subject subject = SecurityUtils.getSubject();

    RestResult<String> restResult = new RestResult<String>();
    restResult.success().setMsg("登录成功");

    try {
        if (!subject.isAuthenticated()) {
            token.setRememberMe(false);
            subject.login(token);

            User u = userService.findByName(loginName);
            subject.getSession(true).setAttribute(Consts.SESSION_USER, u);
        }
        if (getParaToBoolean("rememberMe") != null && getParaToBoolean("rememberMe")) {
            setCookie("loginName", loginName, 60 * 60 * 24 * 7);
        } else {
            removeCookie("loginName");
        }
    } catch (UnknownAccountException une) {
        restResult.error("用户名不存在");
    } catch (LockedAccountException lae) {
        restResult.error("用户被锁定");
    } catch (IncorrectCredentialsException ine) {
        restResult.error("用户名或密码不正确");
    } catch (ExcessiveAttemptsException exe) {
        restResult.error("账户密码错误次数过多,账户已被限制登录1小时");
    } catch (Exception e) {
        e.printStackTrace();
        restResult.error("服务异常,请稍后重试");
    }

    renderJson(restResult);
}
 
Example #21
Source File: AuthenticationInterceptor.java    From EasyEE with MIT License 5 votes vote down vote up
@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());
	}
 
Example #22
Source File: AuthenticationInterceptor.java    From EasyEE with MIT License 5 votes vote down vote up
@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());
	}
 
Example #23
Source File: AuthenticationInterceptor.java    From EasyEE with MIT License 5 votes vote down vote up
@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());
	}
 
Example #24
Source File: AuthenticationInterceptor.java    From EasyEE with MIT License 5 votes vote down vote up
@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());
	}
 
Example #25
Source File: ShiroDBRealm.java    From tianti with Apache License 2.0 5 votes vote down vote up
/**
 * 验证当前用户
 */
@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;
}
 
Example #26
Source File: AuthenticationInterceptor.java    From EasyEE with MIT License 5 votes vote down vote up
@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());
	}
 
Example #27
Source File: BasicAuthenticator.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Override
public java.util.Optional<Principal> authenticate(BasicCredentials credentials) throws AuthenticationException {
  Subject subject = SecurityUtils.getSubject();
  try {
    subject.login(new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword(), false));
    User user = new User(subject);
    return Optional.of(user);
  } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
    logger.log(Level.WARNING, e.getMessage(), e);
  } catch (org.apache.shiro.authc.AuthenticationException ae) {
    logger.log(Level.WARNING, ae.getMessage(), ae);
  }
  return Optional.empty();
}
 
Example #28
Source File: WebExceptionHandler.java    From Shiro-Action with MIT License 5 votes vote down vote up
@ExceptionHandler
public String lockedAccount(LockedAccountException e) {
    if (log.isDebugEnabled()) {
        log.debug("账号已锁定");
    }
    return generateErrorInfo(ResultBean.FAIL, "账号已锁定");
}
 
Example #29
Source File: StandaloneShiroTest.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Test
public void test()
{
    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    Session session = currentUser.getSession();
    session.setAttribute( "someKey", "aValue" );
    String value = ( String ) session.getAttribute( "someKey" );
    assertEquals( "aValue", value );
    LOG.info( "Retrieved the correct value! [" + value + "]" );

    // let's login the current user so we can check against roles and permissions:
    if ( !currentUser.isAuthenticated() ) {
        UsernamePasswordToken token = new UsernamePasswordToken( "lonestarr", "vespa" );
        token.setRememberMe( true );
        try {
            currentUser.login( token );
        } catch ( UnknownAccountException uae ) {
            fail( "There is no user with username of " + token.getPrincipal() );
        } catch ( IncorrectCredentialsException ice ) {
            fail( "Password for account " + token.getPrincipal() + " was incorrect!" );
        } catch ( LockedAccountException lae ) {
            fail( "The account for username " + token.getPrincipal() + " is locked.  "
                  + "Please contact your administrator to unlock it." );
        } // ... catch more exceptions here (maybe custom ones specific to your application?
        catch ( AuthenticationException ae ) {
            //unexpected condition?  error?
            throw ae;
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    assertNotNull( currentUser.getPrincipal() );
    LOG.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );

    //test a role:
    if ( currentUser.hasRole( "schwartz" ) ) {
        LOG.info( "May the Schwartz be with you!" );
    } else {
        fail( "Hello, mere mortal." );
    }

    //test a typed permission (not instance-level)
    if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
        LOG.info( "You may use a lightsaber ring.  Use it wisely." );
    } else {
        fail( "Sorry, lightsaber rings are for schwartz masters only." );
    }

    //a (very powerful) Instance Level permission:
    if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
        LOG.info( "You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                  + "Here are the keys - have fun!" );
    } else {
        fail( "Sorry, you aren't allowed to drive the 'eagle5' winnebago!" );
    }

    //all done - log out!
    currentUser.logout();
}
 
Example #30
Source File: Main.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        Realm realm = new MyCustomRealm();
        SecurityManager securityManager = new DefaultSecurityManager(realm);

        SecurityUtils.setSecurityManager(securityManager);
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
          UsernamePasswordToken token 
            = new UsernamePasswordToken("user", "password");
          token.setRememberMe(true);
          try {
              currentUser.login(token);
          } catch (UnknownAccountException uae) {
              log.error("Username Not Found!", uae);
          } catch (IncorrectCredentialsException ice) {
              log.error("Invalid Credentials!", ice);
          } catch (LockedAccountException lae) {
              log.error("Your Account is Locked!", lae);
          } catch (AuthenticationException ae) {
              log.error("Unexpected Error!", ae);
          }
        }

        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        if (currentUser.hasRole("admin")) {
            log.info("Welcome Admin");
        } else if(currentUser.hasRole("editor")) {
            log.info("Welcome, Editor!");
        } else if(currentUser.hasRole("author")) {
            log.info("Welcome, Author");
        } else {
            log.info("Welcome, Guest");
        }

        if(currentUser.isPermitted("articles:compose")) {
            log.info("You can compose an article");
        } else {
            log.info("You are not permitted to compose an article!");
        }

        if(currentUser.isPermitted("articles:save")) {
            log.info("You can save articles");
        } else {
            log.info("You can not save articles");
        }

        if(currentUser.isPermitted("articles:publish")) {
            log.info("You can publish articles");
        } else {
            log.info("You can not publish articles");
        }

        Session session = currentUser.getSession();
        session.setAttribute("key", "value");
        String value = (String) session.getAttribute("key");
        if (value.equals("value")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        currentUser.logout();

        System.exit(0);
    }