package org.keycloak.adapters.springsecurity.authentication;

import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.springsecurity.AdapterDeploymentContextBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Logs the current user out of Keycloak.
 *
 * @author <a href="mailto:srossillo@smartling.com">Scott Rossillo</a>
 * @version $Revision: 1 $
 */
public class KeycloakLogoutHandler implements LogoutHandler {

    public static final String SSO_LOGOUT_COMPLETE_PARAM = "sso_complete";
    private static final Logger log = LoggerFactory.getLogger(KeycloakLogoutHandler.class);

    private AdapterDeploymentContextBean deploymentContextBean;

    public KeycloakLogoutHandler(AdapterDeploymentContextBean deploymentContextBean) {
        Assert.notNull(deploymentContextBean);
        this.deploymentContextBean = deploymentContextBean;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        if (authentication instanceof AnonymousAuthenticationToken) {
            log.warn("Attempt to log out an anonymous authentication");
            return;
        }

        if (Boolean.valueOf(request.getParameter(SSO_LOGOUT_COMPLETE_PARAM))) {
            // already logged out
            return;
        }

        try {
            handleSingleSignOut(request, response);
        } catch (IOException e) {
            throw new IllegalStateException("Unable to redirect to SSO url!", e);
        }

    }

    protected String createRedirectUrl(HttpServletRequest request) {

        return UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString())
                .replaceQueryParam(SSO_LOGOUT_COMPLETE_PARAM, true).build().toUriString();
    }

    protected void handleSingleSignOut(HttpServletRequest request, HttpServletResponse response) throws IOException {

        KeycloakDeployment deployment = deploymentContextBean.getDeployment();
        String redirectUrl = createRedirectUrl(request);

        response.sendRedirect(deployment.getLogoutUrl().queryParam("redirect_uri", redirectUrl).build().toASCIIString());
    }
}

@@ -137,50 +137,194 @@
 ers.
-springsecurity.AdapterDeploymentContextBea
+RefreshableKeycloakSecurityContext;%0Aimport org.keycloak.adapters.springsecurity.AdapterDeploymentContextBean;%0Aimport org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToke
 n;%0Ai
@@ -517,16 +517,88 @@
 cation;%0A
+import org.springframework.security.core.context.SecurityContextHolder;%0A
 import o
@@ -709,66 +709,8 @@
 ert;
-%0Aimport org.springframework.web.util.UriComponentsBuilder;
 %0A%0Aim
@@ -1047,83 +1047,8 @@
  %7B%0A%0A
-    public static final String SSO_LOGOUT_COMPLETE_PARAM = %22sso_complete%22;%0A
     
@@ -1708,153 +1708,8 @@
  %7D%0A%0A
-        if (Boolean.valueOf(request.getParameter(SSO_LOGOUT_COMPLETE_PARAM))) %7B%0A            // already logged out%0A            return;%0A        %7D%0A%0A
     
@@ -1863,27 +1863,33 @@
  to 
-redirect to SSO url
+make logout admin request
 !%22, 
@@ -1928,32 +1928,32 @@
 ted 
-String createRedirectUrl
+void handleSingleSignOut
 (Htt
@@ -1979,313 +1979,200 @@
 uest
-) %7B%0A%0A        return UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString())%0A                .replaceQueryParam(SSO_LOGOUT_COMPLETE_PARAM, true).build().toUriString();%0A    %7D%0A%0A    protected void handleSingleSignOut(HttpServletRequest request, HttpServletResponse response) throws IOExcep
+, HttpServletResponse response) throws IOException %7B%0A%0A        KeycloakAuthenticationToken authentication = (KeycloakAuthenticationToken) SecurityContextHolder.getContext().getAuthentica
 tion
- %7B%0A
+();
 %0A   
@@ -2259,179 +2259,317 @@
     
-String redirectUrl = createRedirectUrl(request);%0A%0A        response.sendRedirect(deployment.getLogoutUrl().queryParam(%22redirect_uri%22, redirectUrl).build().toASCIIString());
+RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) authentication.getAccount().getKeycloakSecurityContext();%0A%0A        try %7B%0A            session.logout(deployment);%0A        %7D catch (Exception e) %7B%0A            log.error(%22Unable to complete Keycloak single sign out%22, e);%0A        %7D
 %0A   

Use backchannel logout for Spring Security SSO