首先在shiro配置类中注入rememberMe管理器

/**
* cookie对象;
* rememberMeCookie()方法是设置Cookie的生成模版,比如cookie的name,cookie的有效时间等等。
* @return
*/
@Bean
public SimpleCookie rememberMeCookie(){
//System.out.println("ShiroConfiguration.rememberMeCookie()");
//这个参数是cookie的名称,对应前端的checkbox的name = rememberMe
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
//<!-- 记住我cookie生效时间30天 ,单位秒;-->
simpleCookie.setMaxAge(259200);
return simpleCookie;
} /**
* cookie管理对象;
* rememberMeManager()方法是生成rememberMe管理器,而且要将这个rememberMe管理器设置到securityManager中
* @return
*/
@Bean
public CookieRememberMeManager rememberMeManager(){
//System.out.println("ShiroConfiguration.rememberMeManager()");
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
//rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)
cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
return cookieRememberMeManager;
} @Bean(name = "securityManager")
public DefaultWebSecurityManager defaultWebSecurityManager(MyShiroRealm realm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//设置realm
securityManager.setRealm(realm);
//用户授权/认证信息Cache, 采用EhCache缓存
securityManager.setCacheManager(getEhCacheManager());
//注入记住我管理器
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}

并且配置记住我或认证通过可以访问的地址

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

login.jsp加上了记住我的input标签:

<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>

后台的登录处理方法参数用boolean类型接收,并且在得到身份验证Token时传入rememberMe参数

@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(@Valid User user, BindingResult bindingResult,boolean rememberMe,
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";
}
//对密码进行加密后验证
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
Session session = currentUser.getSession();
User tUser = permissionService.findByUserEmail(email);
session.setAttribute("currentUser",tUser);
return "/welcome";
}else{
token.clear();
return "redirect:login";
}
}

启动项目后,第一次输入http://localhost:8080/boot/后跳转到login登录页面,当登录成功后,关闭浏览器重新打开再输入地址后,不需要重新登录,直接跳转。

SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)的更多相关文章

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

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

  2. SpringBoot:整合Shiro

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

  3. SpringBoot学习:整合shiro(rememberMe记住我功能)

    项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821 首先在shiro配置类中注入rememberMe管理器 /** * cookie对象; ...

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

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

  5. Shiro自动登录

    Shiro RememberMe spring.xml <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager& ...

  6. Springboot学习:SpringMVC自动配置

    Spring MVC auto-configuration Spring Boot 自动配置好了SpringMVC 以下是SpringBoot对SpringMVC的默认配置:==(WebMvcAuto ...

  7. shiro 自动登录

    1.出现的错误:did not match the expected credentials---密码不匹配,后来自己写密码验证,其实作用不大: 配置 <!-- Shiro权限过滤过滤器定义 - ...

  8. h5本地存储登录页面实现记住密码功能

    <!DOCTYPE html> <html> <head> <title></title> </head> <style ...

  9. SpringBoot学习- 8、整合Shiro

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

随机推荐

  1. GridView 绑定数据的常用指定格式。

    形式 语法 结果 注释 数字 {0:N2} 12.36   数字 {0:N0} 13   货币 {0:c2} $12.36   货币 {0:c4} $12.3656   货币 "¥{0:N2 ...

  2. java websocket @ServerEndpoint注解说明

    http://www.blogjava.net/qbna350816/archive/2016/07/24/431302.html https://segmentfault.com/q/1010000 ...

  3. ylbtech-Tool:

    ylbtech-Tool: 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部     6.返回顶部   7.返回顶部   8.返回顶部   9.返回顶部   10. ...

  4. 文件读取错误UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 884: invalid start byte

    参考: https://segmentfault.com/q/1010000004268196/a-1020000004269556 ubuntu下Python3使用open('filename', ...

  5. 利用VMware在虚拟机上安装Zookeeper集群

    http://blog.csdn.net/u010246789/article/details/52101026 利用VMware在虚拟机上安装Zookeeper集群 pasting

  6. linux下scp用法

    scp 对拷文件夹 和 文件夹下的所有文件 对拷文件并重命名 对拷文件夹 (包括文件夹本身) scp -r   /home/wwwroot/www/charts/util root@192.168.1 ...

  7. 这个移动通讯中 DB 、DBm 、瓦的基本知识的问题:

    1.对于无线工程师来说更常用分贝dBm这个单位,dBm单位表示相对于1毫瓦的分贝数,dBm和W之间的关系是:dBm=10*lg(mW)1w的功率,换算成dBm就是10×lg1000=30dBm.2w是 ...

  8. 【转】iOS9适配 之 关于info.plist 第三方登录 添加URL Schemes白名单

    近期苹果公司iOS 9系统策略更新,限制了http协议的访问,此外应用需要在“Info.plist”中将要使用的URL Schemes列为白名单,才可正常检查其他应用是否安装. 受此影响,当你的应用在 ...

  9. CentOS7 安装svn

    1 yum install subversion 2 运行 svn --version 报错 svn: error while loading shared libraries: libaprutil ...

  10. XE: Changing the default http port

    Oracle XE uses the embedded http listener that comes with the XML DB (XDB) to serve http requests. T ...