springboot整合shiro-记住我

springboot整合shiro-记住我,第1张

springboot整合shiro-记住我

源码:https://gitee.com/xxxiaowu/springboot-shiro

首先导入依赖


    org.apache.shiro
    shiro-spring
    1.8.0



    com.github.theborakompanioni
    thymeleaf-extras-shiro
    2.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;
    }

这样就是实现了记住我功能

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5693088.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存