Skip to content

Instantly share code, notes, and snippets.

@Fredx87
Last active February 25, 2021 18:11
Show Gist options
  • Save Fredx87/48fe741eed42efa4e77bd341745084a8 to your computer and use it in GitHub Desktop.
Save Fredx87/48fe741eed42efa4e77bd341745084a8 to your computer and use it in GitHub Desktop.
Swagger UI Keycloak Logout plugin

Swagger UI Keycloak Logout plugin

This is a plugin for Swagger UI that integrates the logout process with Keycloak.

When the user clicks "Logout" the logout page of Keycloak is called and then the user session is removed from Keycloak. To use this plugin you need to include the keycloak-logout.js file in dist/index.html and place oauth2-logout.html in the dist folder.

The logout URL is taken from the authorizationUrl removing the auth string and replacing it with the logout string.

Rember to add OAuthLogoutPlugin to the plugins section of SwaggerUi configuration:

const ui = SwaggerUIBundle({
    ...
    plugins: [ OAuthLogoutPlugin ],
    ...
});

The oauth2-logout.html file is needed only for closing the opened popup. We can't use the default oauth2-redirect.html since it performs some controls that don't work after logout.

function OAuthLogoutPlugin() {
var lastAuthUrl = null;
return {
statePlugins: {
auth: {
wrapActions: {
authorizeOauth2: (originalAction, system) => (payload) => {
originalAction(payload);
var auth = payload.auth;
if (auth) {
lastAuthUrl = auth.schema.get('authorizationUrl');
}
},
logout: (originalAction, system) => (payload) => {
originalAction(payload);
if (lastAuthUrl) {
var redirectUrl = location.protocol + "//" + location.host + location.pathname + 'oauth2-logout.html';
var logoutUrl = lastAuthUrl.substring(0, lastAuthUrl.lastIndexOf('/')) + '/logout';
logoutUrl += "?redirect_uri=" + encodeURIComponent(redirectUrl);
window.open(logoutUrl);
}
}
}
}
}
}
}
<!doctype html>
<html lang="en-US">
<body onload="run()">
</body>
</html>
<script>
'use strict';
function run () {
window.close();
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment