Logout

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

Spring Security provides a logout endpoint by default. Once logged in, you can GET /logout to see a default logout confirmation page, or you can POST /logout to initiate logout. This will:

  • clear the ServerCsrfTokenRepository, ServerSecurityContextRepository, and

  • redirect back to the login page

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

Often, you will want to also invalidate the session on logout. To achieve this, you can add the WebSessionServerLogoutHandler to your logout configuration, like so:

  • 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
        }
    }
}