目录
用户登出
编写页面
代码示例
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="container">
<main role="main">
<div class="jumbotron">
<div class="col-sm-12 mx-auto text-center">
<p>系统登出成功。如您想继续其它操作,请重新<a href="login.html" th:href="@{/login}">登录</a>。</p>
</div>
</div>
</main>
</div>
</body>
</html>
主要
在Spring Security中的config文件中修改一下configure方法中改成如下代码
http.logoutSuccessUrl("/logout_success").permitAll()
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin().loginPage("/login").defaultSuccessUrl("/index").permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.logout()
//下面这个是主要代码,这是Spring Security中给下面这个html开放权限设置
.logoutSuccessUrl("/logout_success")
.permitAll()
.and()
.csrf().disable()
;
}
在写一个Controller实现类访问到logout_success页面即可
实现展示图如下,当我们登陆进去主页面之后点击退出登陆按钮会跳转到上面这个页面
SuccessHandler用法
微信中有一个登陆过后会有一个提示,比如异地登陆的风险提示,这里做一个简单的案例
在刚刚的config文件中在加入一串代码,如下
主要
http.formLogin().successHandler(customAuthenticationSuccessHandler())
加入AuthenticationSuccessHandler方法
加入之后在此类中在写入一个AuthenticationSuccessHandler方法,具体代码如下
@Bean
public AuthenticationSuccessHandler customAuthenticationSuccessHandler() {
//编写一个CustomSavedRequestAwareAuthenticationSuccessHandler,这个类用于获取想要的信息
CustomSavedRequestAwareAuthenticationSuccessHandler customSavedRequestAwareAuthenticationSuccessHandler = new CustomSavedRequestAwareAuthenticationSuccessHandler();
customSavedRequestAwareAuthenticationSuccessHandler.setDefaultTargetUrl("/index");
return customSavedRequestAwareAuthenticationSuccessHandler;
}
CustomSavedRequestAwareAuthenticationSuccessHandler类具体代码如下
编写CustomSavedRequestAwareAuthenticationSuccessHandler实现类
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
/**
* @Author uncletj
* @Date 2021/3/18 9:24
* @Version SpringBoot 2.2.2
* @projectName
*/
public class CustomSavedRequestAwareAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
//这个类我只是写了一个简单的输出语句,根据项目具体需求可编写方法加入到此方法内进行实现(如:微信提示,短信提示等)
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
super.onAuthenticationSuccess(request, response, authentication);
this.logger.info(String.format("IP %s,用户 %s, 于 %s 成功登录系统,如非本人操作,请立即访问网页修改密码", request.getRemoteHost(), authentication.getName(), LocalDateTime.now()));
}
}
紧接着就启动项目测试看一下效果如何
当我们登录进来之后后台应该需要执行刚刚所编写的方法,效果如下