remember me实现
1 修改ShiroConfig
秘钥长度为16位,使用的时AES加密。
@Configuration public class ShiroConfig { @Autowired private MyRealm myRealm; @Bean public DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5"); hashedCredentialsMatcher.setHashIterations(2); myRealm.setCredentialsMatcher(hashedCredentialsMatcher); manager.setRealm(myRealm); manager.setRememberMeManager(rememberMeManager()); return manager; } /** * cookie 属性设置 */ public SimpleCookie rememberMeCookie() { SimpleCookie cookie = new SimpleCookie("rememberMe"); // cookie.setDomain(domain); cookie.setPath("/"); cookie.setHttpOnly(true); cookie.setMaxAge(30 * 24 * 60 * 60); return cookie; } /** * 记住我 */ public CookieRememberMeManager rememberMeManager() { CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); cookieRememberMeManager.setCookie(rememberMeCookie()); cookieRememberMeManager.setCipherKey(Base64.decode("MTIzNDU2NzgxMjM0NTY3OA==")); return cookieRememberMeManager; } @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition(); definition.addPathDefinition("/doLogin", "anon"); definition.addPathDefinition("/logout", "logout"); definition.addPathDefinition("/**", "user"); return definition; } @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } }
2 修改控制器方法
修改控制doLogin方法,在UsernamePasswordToken中添加第三个参数。表示是否启用remember me功能。
此功能应该在页面中添加一个复选框,代码中直接假设用户勾选了复选框
@RequestMapping("/doLogin") public String showLogin(User user){ Subject subject = SecurityUtils.getSubject(); try { //添加第三个参数,表示是否启用rememberme功能 subject.login(new UsernamePasswordToken(user.getUsername(),user.getPassword(),true)); return "redirect:/showIndex"; } catch (Exception e) { e.printStackTrace(); } return "redirect:/showLogin"; }