Logout

Spring Security 默认提供注销端点。登录后,你可以 GET /logout 查看默认的注销确认页面,或 POST /logout 初始化注销。它将:

  • 清除 ServerCsrfTokenRepository、`ServerSecurityContextRepository`以及

  • 重定向回登录页面

在注销时,通常还想使会话失效。为实现它,可以将 WebSessionServerLogoutHandler 添加到注销配置中,如下所示:

  • Java

  • Kotlin

@Bean
SecurityWebFilterChain http(ServerHttpSecurity http) throws Exception {
    DelegatingServerLogoutHandler logoutHandler = new DelegatingServerLogoutHandler(
            new SecurityContextServerLogoutHandler(), new WebSessionServerLogoutHandler()
    );

    http
        .authorizeExchange((exchange) -> exchange.anyExchange().authenticated())
        .logout((logout) -> logout.logoutHandler(logoutHandler));

    return http.build();
}
@Bean
fun http(http: ServerHttpSecurity): SecurityWebFilterChain {
    val customLogoutHandler = DelegatingServerLogoutHandler(
        SecurityContextServerLogoutHandler(), WebSessionServerLogoutHandler()
    )

    return http {
        authorizeExchange {
            authorize(anyExchange, authenticated)
        }
        logout {
            logoutHandler = customLogoutHandler
        }
    }
}