Skip to content

Instantly share code, notes, and snippets.

@arnabdas
Created August 17, 2021 08:03
Show Gist options
  • Save arnabdas/27e667d1345e2a23d8fec297606dcb2b to your computer and use it in GitHub Desktop.
Save arnabdas/27e667d1345e2a23d8fec297606dcb2b to your computer and use it in GitHub Desktop.
Keycloak Authentication - Implicit Flow
(function () {
"use strict";
var t = setInterval(() => {
if(window.keycloak) {
clearInterval(t);
var msg = 'Successfully logged in...';
var msgEl = document.getElementsByClassName("login-message")[0];
msgEl.innerHTML = msg;
msgEl.textContent = msg;
}
}, 500);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Demo Login</title>
</head>
<body onload="initKeycloak()">
<span class="login-message">Logging you in...</span>
<script src="https://<keycloak-instance>/auth/js/keycloak.js"></script>
<script>
function initKeycloak() {
var keycloak = new Keycloak();
keycloak
.init({
onLoad: "login-required",
})
.then(function (authenticated) {
alert(authenticated ? "authenticated" : "not authenticated");
window.keycloak = keycloak;
})
.catch(function () {
alert("failed to initialize");
});
}
</script>
<script src="./app.js"></script>
</body>
</html>

keycloak.json should be downloaded from the Keycloak server admin console. It will be of the following format.

{
  "realm": "App-Name",
  "auth-server-url": "https://<keycloak-instance>/auth/",
  "ssl-required": "external",
  "resource": "<resource-id>",
  "clientId": "<client-id>",
  "public-client": true,
  "confidential-port": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment