Shiro RememberMe
spring.xml
<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
<property name="realm" ref="realm" />
<property name="sessionManager" ref="sessionManager" />
<property name="rememberMeManager" ref="cookieRememberMeManager" />
</bean>
<bean class="com.imooc.cache.RedisCacheManager" id="cacheManager" />
<bean class="org.apache.shiro.web.mgt.CookieRememberMeManager" id="cookieRememberMeManager">
<property name="cookie" ref="cookie" />
</bean>
<bean class="org.apache.shiro.web.servlet.SimpleCookie" id="cookie">
<construtor-arg value="rememberMe" />
<property name="maxAge" value="20000000" />
</bean>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="subLogin" method="post">
用户名:<input type="text" name="username" /><br>
密码:<input type="password" name="password" /><br>
<input type="checkbox" name="rememberMe" />记住我<br>
<input type="submit" value="登录">
</form>
</body>
</html>
User.java
public class User {
private String username;
private String password;
private boolean rememberMe;
public boolean isRememberMe() {
return rememberMe;
}
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserController.java
@Controller
public class UserController {
@RequestMapping(value = "/subLogin", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public String subLogin(User user) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
try {
token.setRememberMe(user.isRememberMe());
subject.login(token);
} catch (AuthenticationException e) {
return e.getMessage();
}
if (subject.hasRole("admin")) {
return "有admin权限";
}
return "无admin权限";
}
}