Skip to content

Commit

Permalink
Update Keycloak SPA example as the current one wasn't working
Browse files Browse the repository at this point in the history
  • Loading branch information
jedla97 committed Jan 22, 2025
1 parent c5ae9ab commit ee47731
Showing 1 changed file with 31 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -411,14 +411,28 @@ For example, if you work with Keycloak, you can use `keycloak.js` to authenticat
<head>
<title>keycloak-spa</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="http://localhost:8180/js/keycloak.js"></script>
<script>
var keycloak = new Keycloak();
keycloak.init({onLoad: 'login-required'}).success(function () {
<script type="importmap">
{
"imports": {
"keycloak-js": "https://cdn.jsdelivr.net/npm/[email protected]/lib/keycloak.js"
}
}
</script>
<script type="module">
import Keycloak from "keycloak-js";
const keycloak = new Keycloak({
url: 'http://localhost:8180',
realm: 'quarkus',
clientId: 'quarkus-app'
});
await keycloak.init({onLoad: 'login-required'}).then(function () {
console.log('User is now authenticated.');
}).error(function () {
window.location.reload();
}).catch(function () {
console.log('User is NOT authenticated.');
});
function makeAjaxRequest() {
axios.get("/api/hello", {
headers: {
Expand All @@ -436,15 +450,24 @@ For example, if you work with Keycloak, you can use `keycloak.js` to authenticat
window.location.reload();
});
});
}
}
let button = document.getElementById('ajax-request');
button.addEventListener('click', makeAjaxRequest);
</script>
</head>
<body>
<button onclick="makeAjaxRequest()">Request</button>
<button id="ajax-request">Request</button>
</body>
</html>
----

[NOTE]
====
To enable authentication for this SPA Keycloak example, disable *Client authentication* and set *Web origins* to `http://localhost:8080`. These settings allow Keycloak's CORS policy to communicate with your Quarkus application.
The code provides an example of building Quarkus single-page applications integrated with Keycloak. For more details about creating single-page applications integrating Keycloak, refer to the official link:https://www.keycloak.org/securing-apps/javascript-adapter[Keycloak JavaScript adapter documentation].
====

=== Cross-origin resource sharing

If you plan to use your OIDC `service` application from a single-page application running on a different domain, you must configure cross-origin resource sharing (CORS).
Expand Down

0 comments on commit ee47731

Please sign in to comment.