spring security webflux 退出
开启csrf 防护功能后,默认只接受post提交的退出请求
**********************
相关类及接口
ServerHttpSecurity
public class ServerHttpSecurity {
*****************
内部类:ServerHttpSecurity.logoutSpec
public final class LogoutSpec {
private LogoutWebFilter logoutWebFilter; //拦截退出请求
private final SecurityContextServerLogoutHandler DEFAULT_LOGOUT_HANDLER;
private List<ServerLogoutHandler> logoutHandlers;
public ServerHttpSecurity.LogoutSpec logoutHandler(ServerLogoutHandler logoutHandler) {
Assert.notNull(logoutHandler, "logoutHandler cannot be null");
this.logoutHandlers.clear();
return this.addLogoutHandler(logoutHandler);
}
private ServerHttpSecurity.LogoutSpec addLogoutHandler(ServerLogoutHandler logoutHandler) {
Assert.notNull(logoutHandler, "logoutHandler cannot be null");
this.logoutHandlers.add(logoutHandler);
return this;
}
public ServerHttpSecurity.LogoutSpec logoutUrl(String logoutUrl) {
//设置拦截路径,默认为: /logout
Assert.notNull(logoutUrl, "logoutUrl must not be null");
ServerWebExchangeMatcher requiresLogout = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, new String[]{logoutUrl});
return this.requiresLogout(requiresLogout);
}
public ServerHttpSecurity.LogoutSpec requiresLogout(ServerWebExchangeMatcher requiresLogout) {
this.logoutWebFilter.setRequiresLogoutMatcher(requiresLogout);
return this;
}
public ServerHttpSecurity.LogoutSpec logoutSuccessHandler(ServerLogoutSuccessHandler handler) {
this.logoutWebFilter.setLogoutSuccessHandler(handler);
return this;
}
public ServerHttpSecurity and() {
return ServerHttpSecurity.this;
}
public ServerHttpSecurity disable() {
ServerHttpSecurity.this.logout = null;
return this.and();
}
private ServerLogoutHandler createLogoutHandler() {
ServerSecurityContextRepository securityContextRepository = ServerHttpSecurity.this.securityContextRepository;
if (securityContextRepository != null) {
this.DEFAULT_LOGOUT_HANDLER.setSecurityContextRepository(securityContextRepository);
}
if (this.logoutHandlers.isEmpty()) {
return null;
} else {
return (ServerLogoutHandler)(this.logoutHandlers.size() == 1 ? (ServerLogoutHandler)this.logoutHandlers.get(0) : new DelegatingServerLogoutHandler(this.logoutHandlers));
}
}
protected void configure(ServerHttpSecurity http) {
ServerLogoutHandler logoutHandler = this.createLogoutHandler();
if (logoutHandler != null) {
this.logoutWebFilter.setLogoutHandler(logoutHandler);
}
http.addFilterAt(this.logoutWebFilter, SecurityWebFiltersOrder.LOGOUT);
}
private LogoutSpec() {
this.logoutWebFilter = new LogoutWebFilter();
this.DEFAULT_LOGOUT_HANDLER = new SecurityContextServerLogoutHandler();
this.logoutHandlers = new ArrayList(Arrays.asList(this.DEFAULT_LOGOUT_HANDLER));
}
}
LogoutWebFilter
public class LogoutWebFilter implements WebFilter {
private AnonymousAuthenticationToken anonymousAuthenticationToken = new AnonymousAuthenticationToken("key", "anonymous", AuthorityUtils.createAuthorityList(new String[]{"ROLE_ANONYMOUS"}));
private ServerLogoutHandler logoutHandler = new SecurityContextServerLogoutHandler();
private ServerLogoutSuccessHandler logoutSuccessHandler = new RedirectServerLogoutSuccessHandler();
private ServerWebExchangeMatcher requiresLogout;
public LogoutWebFilter() {
this.requiresLogout = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, new String[]{"/logout"});
} //默认拦截post 提交的/logout请求,其余提交方式(Get等)不拦截
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.requiresLogout.matches(exchange).filter((result) -> {
return result.isMatch();
}).switchIfEmpty(chain.filter(exchange).then(Mono.empty())).map((result) -> {
return exchange;
}).flatMap(this::flatMapAuthentication).flatMap((authentication) -> {
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
return this.logout(webFilterExchange, authentication);
});
}
private Mono<Authentication> flatMapAuthentication(ServerWebExchange exchange) {
return exchange.getPrincipal().cast(Authentication.class).defaultIfEmpty(this.anonymousAuthenticationToken);
}
private Mono<Void> logout(WebFilterExchange webFilterExchange, Authentication authentication) {
return this.logoutHandler.logout(webFilterExchange, authentication).then(this.logoutSuccessHandler.onLogoutSuccess(webFilterExchange, authentication)).subscriberContext(ReactiveSecurityContextHolder.clearContext());
}
public void setLogoutSuccessHandler(ServerLogoutSuccessHandler logoutSuccessHandler) {
Assert.notNull(logoutSuccessHandler, "logoutSuccessHandler cannot be null");
this.logoutSuccessHandler = logoutSuccessHandler;
}
public void setLogoutHandler(ServerLogoutHandler logoutHandler) {
Assert.notNull(logoutHandler, "logoutHandler must not be null");
this.logoutHandler = logoutHandler;
}
public void setRequiresLogoutMatcher(ServerWebExchangeMatcher requiresLogoutMatcher) {
Assert.notNull(requiresLogoutMatcher, "requiresLogoutMatcher must not be null");
this.requiresLogout = requiresLogoutMatcher;
}
}
ServerLogoutSuccessHandler:成功退出的处理接口
public interface ServerLogoutSuccessHandler {
Mono<Void> onLogoutSuccess(WebFilterExchange var1, Authentication var2);
}
RedirectServerLogoutSuccessHandler:成功退出默认实现类
public class RedirectServerLogoutSuccessHandler implements ServerLogoutSuccessHandler {
public static final String DEFAULT_LOGOUT_SUCCESS_URL = "/login?logout";
private URI logoutSuccessUrl = URI.create("/login?logout");
private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
public RedirectServerLogoutSuccessHandler() {
}
public Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication) {
return this.redirectStrategy.sendRedirect(exchange.getExchange(), this.logoutSuccessUrl);
}
public void setLogoutSuccessUrl(URI logoutSuccessUrl) {
Assert.notNull(logoutSuccessUrl, "logoutSuccessUrl cannot be null");
this.logoutSuccessUrl = logoutSuccessUrl;
}
}
**********************
示例
*****************
config 层
WebSecurityConfig
@Configuration
public class WebSecurityConfig {
@Bean
public MapReactiveUserDetailsService initMapReactiveUserDetailsService(){
UserDetails userDetails= User.builder().username("gtlx")
.passwordEncoder(initPasswordEncoder()::encode)
.password("123456")
.authorities("ROLE_USER")
.build();
return new MapReactiveUserDetailsService(userDetails);
}
@Bean
public SecurityWebFilterChain initSecurityWebFilterChain(ServerHttpSecurity http){
http.formLogin().loginPage("/login")
.and().authorizeExchange()
.pathMatchers("/hello").hasAuthority("ROLE_USER")
.pathMatchers("/**").permitAll();
http.logout().logoutSuccessHandler(initServerLogoutSuccessHandler());
return http.build();
}
@Bean
public PasswordEncoder initPasswordEncoder(){
return new BCryptPasswordEncoder();
}
private ServerLogoutSuccessHandler initServerLogoutSuccessHandler(){
RedirectServerLogoutSuccessHandler serverLogoutSuccessHandler=new RedirectServerLogoutSuccessHandler();
serverLogoutSuccessHandler.setLogoutSuccessUrl(URI.create("/logout/success"));
return serverLogoutSuccessHandler;
}
}
*****************
controller 层
RedirectController
@Controller
public class RedirectController {
@RequestMapping("/hello2")
public String hello2(){
return "hello2";
}
}
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(Principal principal){
return "hello "+principal.getName();
}
@RequestMapping("/hello8")
public String hello3(ServerWebExchange exchange){
AtomicReference<String> result = new AtomicReference<>();
exchange.getFormData().subscribe(map ->{
System.out.println("name:"+map.getFirst("name"));
System.out.println("age:"+map.getFirst("age"));
result.set(map.getFirst("name")+" "+map.getFirst("age"));
});
return result.get();
}
@RequestMapping("/logout/success")
public String logout(){
return "logout success";
}
}
*****************
前端页面
hello2.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#logout").click(function () {
$("#logout_button").click();
})
})
</script>
</head>
<body>
<form th:action="@{/logout}" method="post" th:align="center">
<button id="logout_button" style="display: none">退出</button>
</form>
<form th:action="@{/hello8}" method="post" th:align="center">
name:<input type="text" name="name"><br>
age :<input type="text" name="age"><br>
<button> 提交 </button>
</form>
</body>
</html>
**********************
使用测试
localhost:8080/hello2
点击退出,输出:logout success