项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821

(一)验证码

首先login.jsp里增加了获取验证码图片的标签:

<body style="margin-left: 500px">
<h1 style="margin-left: 30px">登录页面----</h1>
<form action="<%=basePath%>/login" method="post">
用户名 : <input type="text" name="email" id="email"/><br>
密码: <input type="password" name="pswd" id="pswd"/><br>
验证码:<input type="text" name="gifCode" id="gifCode"/>
<img alt="验证码" src="<%=basePath%>gif/getGifCode"><br>
<input type="checkbox" name="rememberMe" />记住我<br>
<input style="margin-left: 100px" type="submit" value="登录"/><input style="left: 50px" onclick="register()" type="button" value="注册"/>
</form>
<h1 style="color: red">${message }</h1>
</body>

获取图片是请求后台,所以需要在shiro配置类中配置该url可以直接匿名访问:

/**
* 加载ShiroFilter权限控制规则
*/
private void loadShiroFilterChain(ShiroFilterFactoryBean factoryBean) {
/**下面这些规则配置最好配置到配置文件中*/
Map<String, String> filterChainMap = new LinkedHashMap<String, String>();
//配置记住我或认证通过可以访问的地址
filterChainMap.put("/index", "user");
filterChainMap.put("/", "user");
/** authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器
* org.apache.shiro.web.filter.authc.FormAuthenticationFilter */
//filterChainMap.put("/tUser", "authc");//输入http://localhost:8080/myEra/tUser会跳到登录页面
//filterChainMap.put("/tUser/edit/**", "authc,perms[user:edit]");
// anon:它对应的过滤器里面是空的,什么都没做,可以理解为不拦截
//authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问
filterChainMap.put("/permission/userInsert", "anon");
filterChainMap.put("/error", "anon");
filterChainMap.put("/tUser/insert","anon");
filterChainMap.put("/gif/getGifCode","anon");
filterChainMap.put("/**", "authc"); factoryBean.setFilterChainDefinitionMap(filterChainMap);
}

中的filterChainMap.put("/gif/getGifCode","anon");

后台返回验证码前需把该验证码放入session中:

@Controller
@RequestMapping("gif")
public class GifCodeController { /**
* 获取验证码(Gif版本)
* @param response
*/
@RequestMapping(value="/getGifCode",method= RequestMethod.GET)
public void getGifCode(HttpServletResponse response, HttpServletRequest request){
try {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/gif");
/**
* gif格式动画验证码
* 宽,高,位数。
*/
Captcha captcha = new GifCaptcha(146,33,4);
//输出
captcha.out(response.getOutputStream());
HttpSession session = request.getSession(true);
//存入Session
session.setAttribute("gifCode",captcha.text().toLowerCase());
} catch (Exception e) {
System.err.println("获取验证码异常:"+e.getMessage());
}
} }

这里生成验证码的类可以在我的项目里找到。

进入后台登录方法后,直接传入String类型的参数,需要把输入的验证码和session中保存的验证码对比:

@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(@Valid User user, boolean rememberMe,String gifCode,
BindingResult bindingResult, RedirectAttributes redirectAttributes){
if(bindingResult.hasErrors()){
return "redirect:login";
}
String email = user.getEmail();
if(StringUtils.isBlank(user.getEmail()) || StringUtils.isBlank(user.getPswd())){
logger.info("用户名或密码为空! ");
redirectAttributes.addFlashAttribute("message", "用户名或密码为空!");
return "redirect:login";
}
//判断验证码
if(StringUtils.isBlank(gifCode)){
logger.info("验证码为空了!");
redirectAttributes.addFlashAttribute("message", "验证码不能为空!");
return "redirect:login";
}
Session session = SecurityUtils.getSubject().getSession();
String code = (String) session.getAttribute("gifCode");
if(!gifCode.equalsIgnoreCase(code)){
logger.info("验证码错误!");
redirectAttributes.addFlashAttribute("message", "验证码错误!");
return "redirect:login";
}
//对密码进行加密后验证
UsernamePasswordToken token = new UsernamePasswordToken(user.getEmail(), CommonUtils.encrypt(user.getPswd()),rememberMe);
//获取当前的Subject
Subject currentUser = SecurityUtils.getSubject();
try {
//在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
//每个Realm都能在必要时对提交的AuthenticationTokens作出反应
//所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
logger.info("对用户[" + email + "]进行登录验证..验证开始");
currentUser.login(token);
logger.info("对用户[" + email + "]进行登录验证..验证通过");
}catch(UnknownAccountException uae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,未知账户");
redirectAttributes.addFlashAttribute("message", "未知账户");
}catch(IncorrectCredentialsException ice){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,错误的凭证");
redirectAttributes.addFlashAttribute("message", "密码不正确");
}catch(LockedAccountException lae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,账户已锁定");
redirectAttributes.addFlashAttribute("message", "账户已锁定");
}catch(ExcessiveAttemptsException eae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,错误次数大于5次,账户已锁定");
redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数大于5次,账户已锁定");
}catch (DisabledAccountException sae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,帐号已经禁止登录");
redirectAttributes.addFlashAttribute("message", "帐号已经禁止登录");
}catch(AuthenticationException ae){
//通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
logger.info("对用户[" + email + "]进行登录验证..验证未通过,堆栈轨迹如下");
ae.printStackTrace();
redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
}
//验证是否登录成功
if(currentUser.isAuthenticated()){
logger.info("用户[" + email + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
//把当前用户放入session
User tUser = permissionService.findByUserEmail(email);
session.setAttribute("currentUser",tUser);
return "/welcome";
}else{
token.clear();
return "redirect:login";
}
// 此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
// 登陆失败还到login页面
// return "login";
}

页面展示:

当用户验证码输错提示:

(二)登录次数限制
使用redis缓存存储登录的次数,当用户成功登录后,清空该次数:

@Autowired
private StringRedisTemplate stringRedisTemplate; //用户登录次数计数 redisKey 前缀
private String SHIRO_LOGIN_COUNT = "shiro_login_count_";
//用户登录是否被锁定 一小时 redisKey 前缀
private String SHIRO_IS_LOCK = "shiro_is_lock_"; @RequestMapping(value="/login",method=RequestMethod.POST)
public String login(@Valid User user, boolean rememberMe,String gifCode,
BindingResult bindingResult, RedirectAttributes redirectAttributes){
if(bindingResult.hasErrors()){
return "redirect:login";
}
String email = user.getEmail();
if(StringUtils.isBlank(user.getEmail()) || StringUtils.isBlank(user.getPswd())){
logger.info("用户名或密码为空! ");
redirectAttributes.addFlashAttribute("message", "用户名或密码为空!");
return "redirect:login";
}
//判断验证码
if(StringUtils.isBlank(gifCode)){
logger.info("验证码为空了!");
redirectAttributes.addFlashAttribute("message", "验证码不能为空!");
return "redirect:login";
}
Session session = SecurityUtils.getSubject().getSession();
String code = (String) session.getAttribute("gifCode");
if(!gifCode.equalsIgnoreCase(code)){
logger.info("验证码错误!");
redirectAttributes.addFlashAttribute("message", "验证码错误!");
return "redirect:login";
}
logger.info("进行登录次数验证");
//访问一次,计数一次
ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
if ("LOCK".equals(opsForValue.get(SHIRO_IS_LOCK+email))){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,错误次数大于5次,账户已锁定");
redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数大于5次,账户已锁定");
return "redirect:login";
}
opsForValue.increment(SHIRO_LOGIN_COUNT+email, 1);
//计数大于3时,设置用户被锁定一小时
if(Integer.parseInt(opsForValue.get(SHIRO_LOGIN_COUNT+email))>=5){
opsForValue.set(SHIRO_IS_LOCK+email, "LOCK");
stringRedisTemplate.expire(SHIRO_IS_LOCK+email, 1, TimeUnit.HOURS);
}
//对密码进行加密后验证
UsernamePasswordToken token = new UsernamePasswordToken(user.getEmail(), CommonUtils.encrypt(user.getPswd()),rememberMe);
//获取当前的Subject
Subject currentUser = SecurityUtils.getSubject();
try {
//在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
//每个Realm都能在必要时对提交的AuthenticationTokens作出反应
//所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
logger.info("对用户[" + email + "]进行登录验证..验证开始");
currentUser.login(token);
logger.info("对用户[" + email + "]进行登录验证..验证通过");
}catch(UnknownAccountException uae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,未知账户");
redirectAttributes.addFlashAttribute("message", "未知账户");
}catch(IncorrectCredentialsException ice){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,错误的凭证");
redirectAttributes.addFlashAttribute("message", "密码不正确");
}catch(LockedAccountException lae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,账户已锁定");
redirectAttributes.addFlashAttribute("message", "账户已锁定");
}catch(ExcessiveAttemptsException eae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,错误次数大于5次,账户已锁定");
redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数大于5次,账户已锁定");
}catch (DisabledAccountException sae){
logger.info("对用户[" + email + "]进行登录验证..验证未通过,帐号已经禁止登录");
redirectAttributes.addFlashAttribute("message", "帐号已经禁止登录");
}catch(AuthenticationException ae){
//通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
logger.info("对用户[" + email + "]进行登录验证..验证未通过,堆栈轨迹如下");
ae.printStackTrace();
redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");
}
//验证是否登录成功
if(currentUser.isAuthenticated()){
logger.info("用户[" + email + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
//清空登录计数
opsForValue.set(SHIRO_LOGIN_COUNT+email, "0");
//设置未锁定状态
opsForValue.set(SHIRO_IS_LOCK+email,"UNLOCK");
//把当前用户放入session
User tUser = permissionService.findByUserEmail(email);
session.setAttribute("currentUser",tUser);
return "/welcome";
}else{
token.clear();
return "redirect:login";
}
// 此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
// 登陆失败还到login页面
// return "login";
}

当用户名或密码输错5次后,提示:

验证码和登录次数功能参考博客:http://z77z.oschina.io/

SpringBoot学习:整合shiro(验证码功能和登录次数限制功能)的更多相关文章

  1. SpringBoot:整合Shiro

    目录 1.Shiro简介 1.1.什么是Shiro? 1.2.有哪些功能 1.3.Shiro架构(外部) 1.4.Shiro架构(内部) 2.HelloWorld 3.Shiro整合Spring Bo ...

  2. springboot学习笔记-5 springboot整合shiro

    shiro是一个权限框架,具体的使用可以查看其官网 http://shiro.apache.org/  它提供了很方便的权限认证和登录的功能. 而springboot作为一个开源框架,必然提供了和sh ...

  3. SpringBoot学习- 8、整合Shiro

    SpringBoot学习足迹 Shiro是什么,引自百度百科:Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码和会话管理.使用Shiro的易于理解的API,您可以快 ...

  4. SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理(上)----筑基中期

    写在前面 通过前几篇文章的学习,我们从大体上了解了shiro关于认证和授权方面的应用.在接下来的文章当中,我将通过一个demo,带领大家搭建一个SpringBoot整合Shiro的一个项目开发脚手架, ...

  5. SpringBoot 整合 Shiro 密码登录与邮件验证码登录(多 Realm 认证)

    导入依赖(pom.xml)  <!--整合Shiro安全框架--> <dependency> <groupId>org.apache.shiro</group ...

  6. SpringBoot学习:整合shiro(rememberMe记住我后自动登录session失效解决办法)

    项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 定义一个拦截器,判断用户是通过记住我登录时,查询数据库后台自动登录,同时把用户放入ses ...

  7. springboot整合Shiro功能案例

    Shiro 核心功能案例讲解 基于SpringBoot 有源码 从实战中学习Shiro的用法.本章使用SpringBoot快速搭建项目.整合SiteMesh框架布局页面.整合Shiro框架实现用身份认 ...

  8. SpringBoot整合Shiro实现权限控制,验证码

    本文介绍 SpringBoot 整合 shiro,相对于 Spring Security 而言,shiro 更加简单,没有那么复杂. 目前我的需求是一个博客系统,有用户和管理员两种角色.一个用户可能有 ...

  9. springboot系列(十)springboot整合shiro实现登录认证

    关于shiro的概念和知识本篇不做详细介绍,但是shiro的概念还是需要做做功课的要不无法理解它的运作原理就无法理解使用shiro: 本篇主要讲解如何使用shiro实现登录认证,下篇讲解使用shiro ...

随机推荐

  1. 阅读《C陷阱与缺陷》的知识增量

    版权声明:本文为Focustc原创文章.转载请注明作者及出处. https://blog.csdn.net/caozhankui/article/details/35925939 看完<C陷阱与 ...

  2. springmvc(3)注解

    有疑问可以参考博主其他关于spring mvc的博文 此时直接进行代码的实现 一般的步骤: -加入jar包 -配置DispatcherServlet -加入Spring MVC配置文件 -编写请求的处 ...

  3. MyBatis动态sql语句归纳

    1.删除数据(假删除)并修改时间 <!--根据id删除学生信息(多条)--> <update id="updateStuStatus" parameterType ...

  4. 为什么机器能够学习——PAC Learnability

    机器学习中,我们根据训练集训练一个模型,来对测试数据进行预测.通常我们并不关心模型在训练集上的好坏(即训练误差,in sample error),举个简单例子,我们想要根据前六个月股市行情训练一个模型 ...

  5. Spring时间(Date)类型转换+自定义

    第一种方法:利用内置的 CustomDateEditor(不推荐,每个类都需要定义) 首先,在我们的 Controller 的 InitBinder 里面,注册 CustomEditor //首先初始 ...

  6. vue中使用window.open会在url前自动添加本地服务器的地址bug修复

    不能写成www.baidu.com 需要写成https://www.baidu.com

  7. iOS:文件操作相关(18-03-23更)

    0.iOS文件系统 1.工程内文件 2.文件夹管理 3.文件操作 4.NSCache 附录: 1.沙盒文件夹.文件大小 2.清除沙盒 Library / Cache 下所有数据 3.测试plist 0 ...

  8. jQuery入门简单实现反选与全选

    //html代码<input type="checkbox" id= 'all' value="全选"> 选择全部 一键上路 <input t ...

  9. 微信小程序新版用户授权方式处理

    最新更新(2018-12-27): 最近做了改版,做成默认进来就是首页,然后去判断有没有用户信息,没有的话再去判断用没授权过,如果授权过直接自动去获取,没有的话再跳转到授权页面.因为用户授权主要就是针 ...

  10. 『ACM C++』 Codeforces | 1066A - Points in Segments

    大一生活真 特么 ”丰富多彩“ ,多彩到我要忙到哭泣,身为班长,很多班级的事情需要管理,也是,什么东西都得体验学一学,从学生会主席.团委团总支.社团社长都体验过一番了,现在差个班长也没试过,就来体验了 ...