简体   繁体   中英

Keycloak Spring boot logout from session

Am facing a problem that i don't know how to end the session for a user I already use this one : https://{server}/auth/realms/{Realm}/protocol/openid-connect/logout?id_token_hint={token}& post_logout_redirect_uri={URI TO REDIRECT }

also am using the RealmResource :

        Keycloak keycloak = Keycloak.getInstance(
                "serverURL",
                "realm",
                "username",
                "pass",
                "");

        RealmResource realmResource = keycloak.realm("realm");
        
       ---> realmResource.deleteSession(sessionId); i receive here a error that the Methode not allowed


Your description doesn't contains too much details, but let me present you another way on how to deal with logout in a Spring way.

: I will asume that you know how to inject additional dependencies for this solution to compile & run. :我假设您知道如何为该解决方案注入额外的依赖项以编译和运行。

Why don't you use a well known implementation of ServerLogoutSuccessHandler to logout from Keycloak and remove user session ?

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {

        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(oidcLogoutSuccessHandler());

        return http.build();
    }

    @Bean
    public ServerLogoutSuccessHandler oidcLogoutSuccessHandler() {
        OidcClientInitiatedServerLogoutSuccessHandler successHandler = new OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository);
        successHandler.setPostLogoutRedirectUri(baseUrl);
        return successHandler;
    }

And another way is to use Keycloak API

@Operation(summary = "User logout", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping(value = "/logout/{refresh_token}", produces=MediaType.APPLICATION_JSON_VALUE)
public void logout(@PathVariable String refresh_token) {
    MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
        requestParams.add("client_id", this.clientId);
        requestParams.add("client_secret", this.clientSecret);
        requestParams.add("refresh_token", refreshToken);

        logoutUserSession(requestParams);
}



private void logoutUserSession(MultiValueMap<String, String> requestParams) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestParams, headers);
    String url = String.format("%s/realms/%s/protocol/openid-connect/logout", this.authServerUrl, this.realm);

    restTemplate.postForEntity(url, request, Object.class);
    // got response 204, no content
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM