源码:https://gitee.com/xxxiaowu/springboot-shiro
首先导入依赖
org.apache.shiro shiro-spring1.8.0 com.github.theborakompanioni thymeleaf-extras-shiro2.1.0
在前端添加记住我的按钮
记住我
修改controller,把rememberMe封装到用户登录数据中
@RequestMapping("/login") public String Login(String username, String password, Model model,boolean rememberMe){ System.out.println("======================>"+rememberMe); //获取当前用户 Subject subject = SecurityUtils.getSubject(); //封装用户的登录数据 UsernamePasswordToken token = new UsernamePasswordToken(username,password,rememberMe); try { //执行登录方法 subject.login(token); return "index"; } catch (UnknownAccountException e) { model.addAttribute("msg","用户名不存在"); return "login"; } catch (IncorrectCredentialsException e){ model.addAttribute("msg","密码错误"); return "login"; } }
在ShiroConfig里边注入rememberMe
//DefaultWebSecurityManager @Bean(name = "securityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //关联UserRealm securityManager.setRealm(userRealm); //注入记住我 securityManager.setRememberMeManager(getcookieRememberMeManager()); return securityManager; } @Bean public Simplecookie getRemembercookie(){ //这里边的rememberMe这个参数对应的就是前段记住我input标签的name属性 Simplecookie simplecookie = new Simplecookie("rememberMe"); //这个是cookie过期的时间单位是 秒 simplecookie.setMaxAge(60*60); return simplecookie; } @Bean public cookieRememberMeManager getcookieRememberMeManager(){ cookieRememberMeManager cookieRememberMeManager = new cookieRememberMeManager(); cookieRememberMeManager.setcookie(getRemembercookie()); //cookieRememberMeManager.setCipherKey() // 对rememberMe cookie 加密 长度必须是16位,不安然会报异常 cookieRememberMeManager.setCipherKey("ChengXuYuanYiMei".getBytes()); return cookieRememberMeManager; }
这样就是实现了记住我功能
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)