org.apache.shiro.web.filter.authc.FormAuthenticationFilter Java Examples

The following examples show how to use org.apache.shiro.web.filter.authc.FormAuthenticationFilter. 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: ShiroConfiguration.java    From easyweb with Apache License 2.0 6 votes vote down vote up
@Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(
            DefaultWebSecurityManager securityManager,
            FormAuthenticationFilter formAuthenticationFilter) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/oss/login");
        // 登录成功后要跳转的连接
        shiroFilterFactoryBean.setSuccessUrl("/admin/index");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        Map map = new HashMap<>();
//        map.put("authc",formAuthenticationFilter);
        shiroFilterFactoryBean.setFilters(map);
        loadShiroFilterChain(shiroFilterFactoryBean);
        return shiroFilterFactoryBean;
    }
 
Example #2
Source File: CaptchaFormAuthenticationFilter.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
private void logLoginStatus(ServletRequest request, LoginType loginType) {
	Subject subject = SecurityUtils.getSubject();
	if (subject == null) {
		return;
	}
	ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
	String userId = null;
	if (shiroUser == null && LoginType.登录失败.equals(loginType)) {
		userId = request
				.getParameter(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
	} else {
		userId = shiroUser.loginName;
	}
	if (StringUtils.isBlank(userId)) {
		return;
	}
	LoginIpDto loginIpDto = new LoginIpDto(userId,
			AddressUtil.getIpAddr((HttpServletRequest) request), loginType);
	loginIpService.addLoginIp(loginIpDto);
}
 
Example #3
Source File: ShiroController.java    From niubi-job with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ExceptionForward("/shiro/login")
public String login(HttpServletRequest request) {
    String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
    if (UnknownAccountException.class.getName().equals(exception)) {
        failed("Unknown account.");
    } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
        failed("Incorrect password.");
    } else {
        LoggerHelper.error("unknown error : " + exception);
        failed("Unknown error.");
    }
    return "shiro_login";
}
 
Example #4
Source File: ShiroConfiguration.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean() {
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
    shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());
    shiroFilterFactoryBean.setLoginUrl("/login.html");
    shiroFilterFactoryBean.setSuccessUrl("/home.html");
    shiroFilterFactoryBean.setUnauthorizedUrl("/403.html");

    filterChainDefinitionMap.put("/login.html", "anon");
    filterChainDefinitionMap.put("/v1/api0/image/captcha", "anon"); // 匿名用户可访问
    filterChainDefinitionMap.put("/view/**", "perms");                  // Url权限过滤
    filterChainDefinitionMap.put("/v1/api0/security/login", "anon");    // 登陆用户
    filterChainDefinitionMap.put("/v1/api0/security/logout", "anon");    // 登陆用户
    filterChainDefinitionMap.put("/v1/api0/user*//*", "user");       // 登陆用户
    //>>>>>>
    filterChainDefinitionMap.put("/v1/api0/orgcate*//**//**//**//*", "user");       // 登陆用户
    filterChainDefinitionMap.put("/v1/api0/resource*//**//**//**//*", "user");       // 登陆用户
    filterChainDefinitionMap.put("/v1/api0/role*//**//**//**//*", "user");
    //<<<<<<
    //filterChainDefinitionMap.put("/v1/api0/**/**", "user,perms");       // 登陆用户
    filterChainDefinitionMap.put("/v1/api0/**/**", "user");       // 登陆用户
    filterChainDefinitionMap.put("/home.html", "authc");                // 登陆用户
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

    Map<String, Filter> filters = new HashMap<>();
    filters.put("anon", new AnonymousFilter());
    filters.put("user", new UserFilter());
    filters.put("authc", new FormAuthenticationFilter());
    filters.put("perms", new ShiroPermissionsFilter()); // 自定义权限过滤
    shiroFilterFactoryBean.setFilters(filters);

    return shiroFilterFactoryBean;
}
 
Example #5
Source File: LoginController.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/user/login", method = RequestMethod.GET)
public String login(
		@RequestParam(value = Constant.USER_STATUS_KEY, defaultValue = Constant.USER_NORMAL_STATUS) String userStatus,
		Model model) {

	Subject subject = SecurityUtils.getSubject();

	if (subject != null && subject.isAuthenticated()) {
		return "redirect:/index";
	}

	// 暂时没有业务逻辑进行处理
	if (!Constant.USER_NORMAL_STATUS.equals(userStatus)) {
		model.addAttribute(Constant.USER_STATUS_KEY, userStatus);
		// return "redirect:/user/onlineStatus";
		return "onlineStatus";
	}

	// 获取记住账号的用户信息
	if (subject != null && !subject.isAuthenticated()
			&& subject.isRemembered()) {
		ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
		if (shiroUser != null) {
			// 用户名
			model.addAttribute(
					FormAuthenticationFilter.DEFAULT_USERNAME_PARAM,
					shiroUser.loginName);
		}
	}

	return "login";
}
 
Example #6
Source File: LoginController.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public String fail(
		@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName,
		HttpServletRequest request, Model model) {
	// 用户名
	model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM,
			userName);
	// 登录失败异常
	model.addAttribute(
			FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
			request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME));
	return "login";
}
 
Example #7
Source File: LoginController.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/user/findPassword", method = RequestMethod.POST)
public ModelAndView findPassword(String email, String captcha,
		HttpSession session, ModelAndView model) {

	try {
		model.setViewName("onlineStatus");
		if (StringUtils.isBlank(captcha)) {
			throw new VerificationException("验证码不允许为空");
		}
		String code = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(captcha)) {
			throw new VerificationException("验证码错误");
		}

		if (!StringUtils.checkEmail(email)) {
			throw new VerificationException("邮箱错误");
		}

		CommonResponseDto response = userService.findPassword(email);

		if (response.getResult() == UserConstant.SUCCESS) {
			model.addObject(Constant.USER_STATUS_KEY,
					Constant.USER_FIND_PASSWORD_SUCCESS);
		} else {
			throw new VerificationException(response.getErrorMessage());
		}

	} catch (VerificationException e) {
		// 注册失败异常
		model.addObject(
				FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
				e.getMessage());
		model.addObject(Constant.USER_STATUS_KEY,
				Constant.USER_FIND_PASSWORD_FAIL);
	}
	return model;
}
 
Example #8
Source File: LoginController.java    From spring-boot-quickstart with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
    System.out.println("fail again..");
    model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
    return "account/login";
}
 
Example #9
Source File: UserController.java    From MultimediaDesktop with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/user/register", method = RequestMethod.POST)
public ModelAndView register(ModelAndView model, UserDto user,
		String passwordAgain, String captcha, HttpSession session,
		HttpServletRequest request) {

	try {
		model.addObject("user", user);
		if (StringUtils.isBlank(captcha)) {
			throw new VerificationException("验证码不允许为空");
		}
		String code = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(captcha)) {
			throw new VerificationException("验证码错误");
		}

		if (StringUtils.isBlank(passwordAgain)
				|| StringUtils.isBlank(user.getPassword())
				|| !passwordAgain.equals(user.getPassword())) {
			throw new VerificationException("密码不允许为空或者两次密码输入不匹配");
		}
		user.setRegisterAddress(AddressUtil.getIpAddr(request));
		CommonResponseDto dto = userService.registerUser(user);

		if (UserConstant.SUCCESS != dto.getResult()) {
			throw new VerificationException(dto.getErrorMessage());
		}
		model.addObject(Constant.USER_STATUS_KEY,
				Constant.USER_REGISTER_STATUS);
		model.setViewName("onlineStatus");

	} catch (VerificationException e) {
		// 注册失败异常
		model.addObject(
				FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
				e.getMessage());
		model.addObject("tab", "2");
		model.setViewName("login");
	}
	return model;
}
 
Example #10
Source File: UserController.java    From MultimediaDesktop with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/user/findPassword/{userId}", method = RequestMethod.POST)
public void findPassword(String userIdDigests,
		@PathVariable("userId") String userId, String password,
		String rpassword, String captcha, HttpSession session,
		ModelAndView model) {

	try {

		StringUtils.isValidString(userId, "账号不允许为空");
		StringUtils.isValidString(userIdDigests, "参数错误");
		StringUtils.isValidString(password, "新密码不允许为空");
		StringUtils.isValidString(rpassword, "新密码不允许为空");
		StringUtils.isValidString(captcha, "验证码不允许为空");

		String code = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(captcha)) {
			throw new VerificationException("验证码错误");
		}

		if (!password.equals(rpassword)) {
			throw new VerificationException("两次密码输入不一致");
		}

		String digests = Encodes.encodeHex(Digests.sha1(userId.getBytes()));

		if (!userIdDigests.equals(digests)) {
			// 这儿跳转到错误页面
			model.setViewName("onlineStatus");
			model.addObject(Constant.USER_STATUS_KEY,
					Constant.USER_FIND_PASSWORD_ERROR);
			return;
		}

		CommonResponseDto responseDto = userService.findPassword(userId,
				rpassword);

		if (UserConstant.SUCCESS != responseDto.getResult()) {
			throw new VerificationException(responseDto.getErrorMessage());
		}

		model.setViewName("redirect:/user/login");

	} catch (VerificationException e) {
		model.addObject(
				FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
				e.getMessage());
		model.setViewName("findPassword");
		if(userId!=null){
			model.addObject("userId", userId);
			model.addObject("userIdDigests",
					Encodes.encodeHex(Digests.sha1(userId.getBytes())));
		}
	}

}
 
Example #11
Source File: LoginController.java    From Mario with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
	model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
	return "account/login";
}
 
Example #12
Source File: LoginController.java    From dubai with MIT License 4 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
	model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
	return "passport/loginForm";
}
 
Example #13
Source File: LoginFormController.java    From es with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = {"/{login:login;?.*}"}) //spring3.2.2 bug see  http://jinnianshilongnian.iteye.com/blog/1831408
public String loginForm(HttpServletRequest request, ModelMap model) {

    //表示退出
    if (!StringUtils.isEmpty(request.getParameter("logout"))) {
        model.addAttribute(Constants.MESSAGE, messageSource.getMessage("user.logout.success", null, null));
    }

    //表示用户删除了 @see org.apache.shiro.web.filter.user.SysUserFilter
    if (!StringUtils.isEmpty(request.getParameter("notfound"))) {
        model.addAttribute(Constants.ERROR, messageSource.getMessage("user.notfound", null, null));
    }

    //表示用户被管理员强制退出
    if (!StringUtils.isEmpty(request.getParameter("forcelogout"))) {
        model.addAttribute(Constants.ERROR, messageSource.getMessage("user.forcelogout", null, null));
    }

    //表示用户输入的验证码错误
    if (!StringUtils.isEmpty(request.getParameter("jcaptchaError"))) {
        model.addAttribute(Constants.ERROR, messageSource.getMessage("jcaptcha.validate.error", null, null));
    }


    //表示用户锁定了 @see org.apache.shiro.web.filter.user.SysUserFilter
    if (!StringUtils.isEmpty(request.getParameter("blocked"))) {
        User user = (User) request.getAttribute(Constants.CURRENT_USER);
        String reason = userStatusHistoryService.getLastReason(user);
        model.addAttribute(Constants.ERROR, messageSource.getMessage("user.blocked", new Object[]{reason}, null));
    }

    if (!StringUtils.isEmpty(request.getParameter("unknown"))) {
        model.addAttribute(Constants.ERROR, messageSource.getMessage("user.unknown.error", null, null));
    }

    //登录失败了 提取错误消息
    Exception shiroLoginFailureEx =
            (Exception) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
    if (shiroLoginFailureEx != null) {
        model.addAttribute(Constants.ERROR, shiroLoginFailureEx.getMessage());
    }

    //如果用户直接到登录页面 先退出一下
    //原因:isAccessAllowed实现是subject.isAuthenticated()---->即如果用户验证通过 就允许访问
    // 这样会导致登录一直死循环
    Subject subject = SecurityUtils.getSubject();
    if (subject != null && subject.isAuthenticated()) {
        subject.logout();
    }


    //如果同时存在错误消息 和 普通消息  只保留错误消息
    if (model.containsAttribute(Constants.ERROR)) {
        model.remove(Constants.MESSAGE);
    }

    return "front/login";
}