第一步 :配置spring.xml,配置cookieRememberMeManager
<!--创建SecurityManager对象-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm" />
<property name="sessionManager" ref="sessionManager" />
<property name="cacheManager" ref="cacheManager" />
<property name="rememberMeManager" ref="cookieRememberMeManager" />
</bean>
<bean id="cookieRememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cookie" ref="cookie" />
</bean>
<bean id="cookie" class="org.apache.shiro.web.servlet.SimpleCookie" >
<constructor-arg value="rememberMe" />
<property name="maxAge" value="20000000" />
</bean>
第二步:修改登录页面
<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>
第三步:修改subLogin的Controller,加入token.setRememberMe(Boolean rememberMe)方法
@RequestMapping(path="/subLogin", produces="application/json;charset=utf-8")
@ResponseBody
public String subLogin(User user, boolean rememberMe){
UserRealm userRealm = new UserRealm();
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(userRealm);
//主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
try {
//是否记住密码
token.setRememberMe(rememberMe);
subject.login(token);
} catch (Exception e){
return e.getMessage();
}
//授权认证
if (subject.hasRole("admin")){
return "有admin权限";
}
return "无admin权限";
}
已完成。下次登录时若勾选自动登录,则在cookie存活期间可以免登录。