Version: Next

记住我与登录页定制

记住我

之前,只要登录之后,关闭浏览器,再打开浏览器,就会让用户重新登陆。

很多网站有记住密码功能

  • 配置记住我
@Override
protected void configure(HttpSecurity http) throws Exception {
//认证请求.授权请求.允许所有人.授权请求.具有身份
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没权限就跳转到登录页面
http.formLogin();
//注销
http.logout().logoutSuccessUrl("/");
//记住我
http.rememberMe();
}
  • 配置完后,会发现登录页多了一个记住我功能,关闭浏览器再次打开,发现用户依然存在

    这是通过Cookie实现的

  • 点击注销时,会发现SpringSecurity自动删除了对应Cookie

info

登陆成功后,服务器将cookie发送给浏览器保存,以后登录带着这个cookie,主要通过检查就可以免登陆了。如果点击注销,就会删除这个cookie

定制登陆页

将登录信息发送到哪里也需要配置,login.html必须以POST方式提交请求

<form th:action="@{/login}" method="post">
<div class="field">
<label>Username</label>
<div class="ui left icon input">
<input type="text" placeholder="Username" name="username">
<i class="user icon"></i>
</div>
</div>
<div class="field">
<label>Password</label>
<div class="ui left icon input">
<input type="password" name="password">
<i class="lock icon"></i>
</div>
</div>
<input type="checkbox" name="remember"> 记住我
<input type="submit" class="ui blue submit button"/>
</form>

不用SpringSecurity自带的登陆页面,指定自己的登陆页面,携带前端的username和password属性,指定处理登录验证的路由

@Override
protected void configure(HttpSecurity http) throws Exception {
//认证请求.授权请求.允许所有人.授权请求.具有身份
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没权限就跳转到登录页面
http.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/toLogin")
.loginProcessingUrl("/login");
//注销
http.logout().logoutSuccessUrl("/");
//记住我
http.rememberMe();
}
  • 再登录页增加记住我多选框
<input type="checkbox" name="remember"> 记住我
  • 自定义记住我参数
http.rememberMe().rememberMeParameter("remember");