Java Code Examples for org.apache.shiro.authc.AuthenticationException#printStackTrace()

The following examples show how to use org.apache.shiro.authc.AuthenticationException#printStackTrace() . 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: 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 2
Source File: ShiroSpringController.java    From tutorials with MIT License 6 votes vote down vote up
@RequestMapping( value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
public String login(HttpServletRequest req, UserCredentials cred, RedirectAttributes attr) {

  if(req.getMethod().equals(RequestMethod.GET.toString())) {
    return "login";
  } else {
    Subject subject = SecurityUtils.getSubject();

    if(!subject.isAuthenticated()) {
      UsernamePasswordToken token = new UsernamePasswordToken(
        cred.getUsername(), cred.getPassword(), cred.isRememberMe());
      try {
        subject.login(token);
      } catch (AuthenticationException ae) {
          ae.printStackTrace();
          attr.addFlashAttribute("error", "Invalid Credentials");
          return "redirect:/login";
      }
    }

    return "redirect:/secure";
  }
}
 
Example 3
Source File: LoginController.java    From learnjavabug with MIT License 5 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String username, String password) {
    Subject subject = SecurityUtils.getSubject();
    try {
        subject.login(new UsernamePasswordToken(username, password));
        return "登录成功!";
    } catch (AuthenticationException e) {
        e.printStackTrace();
        return "登录失败!";
    }

}
 
Example 4
Source File: LoginController.java    From learnjavabug with MIT License 5 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String username, String password) {
    Subject subject = SecurityUtils.getSubject();
    try {
        subject.login(new UsernamePasswordToken(username, password));
        return "登录成功!";
    } catch (AuthenticationException e) {
        e.printStackTrace();
        return "登录失败!";
    }

}
 
Example 5
Source File: ShiroExceptionHandler.java    From dts-shop with GNU Lesser General Public License v3.0 4 votes vote down vote up
@ExceptionHandler(AuthenticationException.class)
@ResponseBody
public Object unauthenticatedHandler(AuthenticationException e) {
	e.printStackTrace();
	return ResponseUtil.unlogin();
}
 
Example 6
Source File: EmployeeController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 提交登录信息
 *
 * @param request
 * @return
 */


@RequestMapping(value = "sign/in")
@ResponseBody
@AccessLog(module = AdminModule.SYSTEM, operation = "提交登录信息Admin")
public MessageResult doLogin(@SessionAttribute("username")String username,
                             @SessionAttribute("password")String password,
                             @SessionAttribute("phone")String phone,String code,
                             @RequestParam(value="rememberMe",defaultValue = "true")boolean rememberMe,
                             HttpServletRequest request) {
    Assert.notNull(code,"请输入验证码");
    Assert.isTrue(StringUtils.isNotEmpty(username)&&StringUtils.isNotEmpty(password)&&StringUtils.isNotEmpty(phone),"会话已过期");
    ValueOperations valueOperations = redisTemplate.opsForValue() ;
    Object cacheCode = valueOperations.get(SysConstant.ADMIN_LOGIN_PHONE_PREFIX+phone);
    Assert.notNull(cacheCode,"验证码已经被清除,请重新发送");
    if (!code.equals(cacheCode.toString())) {
        return error("手机验证码错误,请重新输入");
    }
    try {
        log.info("md5Key {}", md5Key);

        //password = Encrypt.MD5(password + md5Key);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,true);
        token.setHost(getRemoteIp(request));
        SecurityUtils.getSubject().login(token);
        valueOperations.getOperations().delete(SysConstant.ADMIN_LOGIN_PHONE_PREFIX+phone);
        Admin admin = (Admin) request.getSession().getAttribute(SysConstant.SESSION_ADMIN);
        //token.setRememberMe(true);

        //获取当前用户的菜单权限
        List<Menu> list;
        if ("root".equalsIgnoreCase(admin.getUsername())) {
            list = sysRoleService.toMenus(sysPermissionService.findAll(), 0L);
        } else {
            list = sysRoleService.toMenus(sysRoleService.getPermissions(admin.getRoleId()), 0L);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("permissions", list);
        map.put("admin", admin);
        return success("登录成功", map);
    } catch (AuthenticationException e) {
        e.printStackTrace();
        return error(e.getMessage());
    }
}
 
Example 7
Source File: EmployeeController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 提交登录信息
 *
 * @param request
 * @return
 */


@RequestMapping(value = "sign/in")
@ResponseBody
@AccessLog(module = AdminModule.SYSTEM, operation = "提交登录信息Admin")
public MessageResult doLogin(@SessionAttribute("username")String username,
                             @SessionAttribute("password")String password,
                             @SessionAttribute("phone")String phone,String code,
                             @RequestParam(value="rememberMe",defaultValue = "true")boolean rememberMe,
                             HttpServletRequest request) {
    Assert.notNull(code,"请输入验证码");
    Assert.isTrue(StringUtils.isNotEmpty(username)&&StringUtils.isNotEmpty(password)&&StringUtils.isNotEmpty(phone),"会话已过期");
    ValueOperations valueOperations = redisTemplate.opsForValue() ;
    Object cacheCode = valueOperations.get(SysConstant.ADMIN_LOGIN_PHONE_PREFIX+phone);
    Assert.notNull(cacheCode,"验证码已经被清除,请重新发送");
    if (!code.equals(cacheCode.toString())) {
        return error("手机验证码错误,请重新输入");
    }
    try {
        log.info("md5Key {}", md5Key);

        //password = Encrypt.MD5(password + md5Key);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,true);
        token.setHost(getRemoteIp(request));
        SecurityUtils.getSubject().login(token);
        valueOperations.getOperations().delete(SysConstant.ADMIN_LOGIN_PHONE_PREFIX+phone);
        Admin admin = (Admin) request.getSession().getAttribute(SysConstant.SESSION_ADMIN);
        //token.setRememberMe(true);

        //获取当前用户的菜单权限
        List<Menu> list;
        if ("root".equalsIgnoreCase(admin.getUsername())) {
            list = sysRoleService.toMenus(sysPermissionService.findAll(), 0L);
        } else {
            list = sysRoleService.toMenus(sysRoleService.getPermissions(admin.getRoleId()), 0L);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("permissions", list);
        map.put("admin", admin);
        return success("登录成功", map);
    } catch (AuthenticationException e) {
        e.printStackTrace();
        return error(e.getMessage());
    }
}
 
Example 8
Source File: ShiroExceptionHandler.java    From mall with MIT License 4 votes vote down vote up
@ExceptionHandler(AuthenticationException.class)
@ResponseBody
public Object unauthenticatedHandler(AuthenticationException e) {
    e.printStackTrace();
    return ResponseUtil.unlogin();
}
 
Example 9
Source File: RestController.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
/**
	 * 前后端分离的情况之下rest风格登录获取TGT ST
	 * @Description:TODO
	 * @author:hsj qq:2356899074
	 * @time:2017年12月1日 下午2:49:40
	 * @param req
	 * @param respon
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/restlogin")
	public String restlogin(HttpServletRequest req,HttpServletResponse respon)throws Exception{
//		return RestFulLogin.validateFromCAS("hsjhsj", "hsjhsj");
		        //校验有没有username和password
                String username = "hsjhsj";
		        UsernamePasswordToken token = new UsernamePasswordToken("hsjhsj","hsjhsj");
		        //获取当前的Subject  
		        Subject currentUser = SecurityUtils.getSubject();  
		        try {  
		            //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查  
		            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应  
		            //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法  
		            logger.info("对用户[" + username + "]进行登录验证..验证开始");  
		            currentUser.login(token);  
		            logger.info("对用户[" + username + "]进行登录验证..验证通过");  
		        }catch(UnknownAccountException uae){  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");  
		            return "403";
		        }catch(IncorrectCredentialsException ice){  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");  
		            return "403";
		        }catch(LockedAccountException lae){  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");  
		            return "403";
		        }catch(ExcessiveAttemptsException eae){  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多"); 
		            return "403";
		        }catch(AuthenticationException ae){  
		            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");  
		            ae.printStackTrace();  
		            return "403";
		        }  
		        //验证是否登录成功  
		        if(currentUser.isAuthenticated()){  
		            logger.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");  
		            return "inde";
		        }else{  
		            token.clear();  
		            return "403";
		        }  
	}
 
Example 10
Source File: UserController.java    From demo-springmvc-shiro with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(String username, String password, HttpServletRequest request){
    System.out.println("-------------------------------------------------------");
    String rand = (String)request.getSession().getAttribute("rand");
    String captcha = WebUtils.getCleanParam(request, "captcha");
    System.out.println("用户["+username+"]登录时输入的验证码为["+captcha+"],HttpSession中的验证码为["+rand+"]");
    if(!StringUtils.equals(rand, captcha)){
        request.setAttribute("message_login", "验证码不正确");
        return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
    }
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    token.setRememberMe(true);
    System.out.print("为验证登录用户而封装的Token:");
    System.out.println(ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
    //获取当前的Subject
    Subject currentUser = SecurityUtils.getSubject();
    try {
        //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
        //每个Realm都能在必要时对提交的AuthenticationTokens作出反应
        //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
        System.out.println("对用户[" + username + "]进行登录验证...验证开始");
        currentUser.login(token);
        System.out.println("对用户[" + username + "]进行登录验证...验证通过");
    }catch(UnknownAccountException uae){
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,未知账户");
        request.setAttribute("message_login", "未知账户");
    }catch(IncorrectCredentialsException ice){
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,错误的凭证");
        request.setAttribute("message_login", "密码不正确");
    }catch(LockedAccountException lae){
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,账户已锁定");
        request.setAttribute("message_login", "账户已锁定");
    }catch(ExcessiveAttemptsException eae){
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,错误次数过多");
        request.setAttribute("message_login", "用户名或密码错误次数过多");
    }catch(AuthenticationException ae){
        //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
        System.out.println("对用户[" + username + "]进行登录验证...验证未通过,堆栈轨迹如下");
        ae.printStackTrace();
        request.setAttribute("message_login", "用户名或密码不正确");
    }
    //验证是否登录成功
    if(currentUser.isAuthenticated()){
        System.out.println("用户[" + username + "]登录认证通过(这里可进行一些认证通过后的系统参数初始化操作)");
        return "main";
    }else{
        token.clear();
        return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
    }
}
 
Example 11
Source File: LoginController.java    From dpCms with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @Title: loginDo 
 * @Description: 平台登录
 * @param @param username
 * @param @param password
 * @return Response 返回类型,如果成功返回跳转的URL
 * @throws
 */
@RequestMapping(value = "/login")
@ResponseBody
public Response login(String username, String password, String logincode , Response response ) {
	String msg = "";
	Subject currentUser = SecurityUtils.getSubject();
	Session session = currentUser.getSession();
	String codeSession = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
	if (StringUtils.isBlank(logincode) || StringUtils.isBlank(codeSession)
			|| !logincode.equals(codeSession)) {
		response.setStateCode(StateCode.LOGIN_FAIL);
		msg = "验证码不正确,朋友!";
	} else {
		AuthenticationToken token = new UsernamePasswordToken(username,password);
		Account account = accountService.findByLoginName(username);
		try {
			currentUser.login(token);
			account.setPassword("");
			// 获取当前登录用户的岗位信息。
			CurrentInfo currentInfo = currentUserInfoService.findCurrentUserInfo(account);
			Employee emplpyee = currentInfo.getEmployee();
			if (emplpyee == null || emplpyee.getDefaultPostId() == null) {
				throw new AccountNoActiceException();
			}
			long defaultPostId = emplpyee.getDefaultPostId();

			// 遍历岗位信息,如果有一个岗位不需要过滤权限,那么这个人不需要过滤权限
			Set<Post> postSet = currentInfo.getPostList();
			Iterator<Post> it = postSet.iterator();
			if (it.hasNext()) {
				Post post = it.next();
				if (post.getNeedFilter() == null) {// 当前登录的员工不需要过滤任何权限
					currentInfo.setNeedFilter(false);
				}
				if (post.getId() == defaultPostId) {// 该人的默认岗位
					currentInfo.setDefaultPostId(defaultPostId);// 保存到SESSION里,快速获取
					currentInfo.setIndexPage(post.getIndexPage());// 保存到SESSION里,快速获取
					currentUser.getSession().setAttribute("currentInfo", currentInfo);
					response.setStateCode(StateCode.OK);
					response.setData("index.html");// 把该人应该跳转的页面返回到客户端
				}
			}

			msg = "登录成功";
		} catch (UnknownAccountException uae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户不存在!";
		} catch (IncorrectCredentialsException ice) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户名或密码错误!";
		} catch (LockedAccountException lae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户为锁定状态!";
		} catch (AuthenticationException ae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			ae.printStackTrace();
			msg = "登录失败!";
		} catch (AccountNoActiceException ana) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "该帐号未激活!";
		} catch (Exception e) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			e.printStackTrace();
			msg = "平台繁忙!";
		}
	}
	response.setMessage(msg);
	currentUser.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
	return response;
}
 
Example 12
Source File: LoginController.java    From jee-universal-bms with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "v1/api0/security/login", method = RequestMethod.POST)
@ResponseBody
public JsonResult login(@RequestParam() String username,
                        @RequestParam() String password,
                        String verifyCode,
                        HttpServletRequest request) {

    JsonResult jsonResult = new JsonResult(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG);
    try {
        if(StringUtils.isBlank(username)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "请输入用户名");
        }
        if(StringUtils.isBlank(password)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "请输入密码");
        }

        User user = userService.getByUsername(username);
        if(user == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "用户不存在");
        }
        if(user.getStatus() != 1) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "该用户已被禁用");
        }
        String salt = user.getSalt();
        password = Utils.encryptPassword(salt, password);
        if (!password.equals(user.getPassword())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "用户名或密码错误");
        }
        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken(username, password));
        if (subject.isAuthenticated()) {
            jsonResult.setMsg("登录成功");
        } else {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "用户名或密码错误");
        }
    } catch (AuthenticationException e){
        jsonResult =  new JsonResult(ResultCode.PARAM_ERROR_CODE, "用户名或密码错误");
        e.printStackTrace();
    }
    return jsonResult;
}