SpringBoot整合Shiro实现RememberMe

接上Springboot Shiro实现用户验
shiro提供了RememberMe功能,用户登录状态不会因为浏览器的关闭而失效,知道cookie过期

更改ShiroConfig

加入cookie管理配置

/**
* cookie对象
* @return
*/
public SimpleCookie rememberMeCookie() {
     
   // 设置cookie名称,对应login.html页面的
   SimpleCookie cookie = new SimpleCookie("rememberMe");
   // 设置cookie的过期时间,单位为秒,这里为一天
   cookie.setMaxAge(86400);
   return cookie;
}

/**
* cookie管理对象
* @return
*/
public CookieRememberMeManager rememberMeManager() {
     
   CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
   cookieRememberMeManager.setCookie(rememberMeCookie());
   // rememberMe cookie加密的密钥 
   cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
   return cookieRememberMeManager;
}

将cookie管理对象配置加入到SecurityManager

    @Bean
    public SecurityManager securityManager() {
     
        // 配置SecurityManager,并注入shiroRealm
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroRealm());
        //cookie管理配置对象
        securityManager.setRememberMeManager(rememberMeManager());
        return securityManager;
    }

修改过滤权限配置
filterChainDefinitionMap.put("/**", "authc");
修改为 filterChainDefinitionMap.put("/**", "user");
因为已经通过验证,不需要在验证
authc与user有何不同

Controller

更改LoginController中的login()方法

@PostMapping("/login")
@ResponseBody
public ResponseBo login(String username, String password, Boolean rememberMe) {
     
   password = MD5Utils.encrypt(username, password);
   UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
   Subject subject = SecurityUtils.getSubject();
   try {
     
       subject.login(token);
       return ResponseBo.ok();
   } catch (UnknownAccountException e) {
     
       return ResponseBo.error(e.getMessage());
   } catch (IncorrectCredentialsException e) {
     
       return ResponseBo.error(e.getMessage());
   } catch (LockedAccountException e) {
     
       return ResponseBo.error(e.getMessage());
   } catch (AuthenticationException e) {
     
       return ResponseBo.error("认证失败!");
   }
}

当rememberMe传入参数true时,shiro会帮我们记住用户的登录状态

你可能感兴趣的:(Spring)