SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)

Stella981
• 阅读 880

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

SpringBoot学习:整合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; }

SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)

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

SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)

/**
  * 加载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); }

SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)

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

SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)

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

SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)

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

SpringBoot学习:整合shiro自动登录功能(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"; } }

SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)

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

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
2年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Easter79 Easter79
2年前
SpringBoot学习:整合shiro自动登录功能(rememberMe记住我功能)
首先在shiro配置类中注入rememberMe管理器!复制代码(https://oscimg.oschina.net/oscnet/675f5689159acfa2c39c91f4df40a00ce0f.gif)/cookie对象;rememberMeCookie()方法是设置Cookie的生成模
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这