Pure Client Javascript Adapter
The Keycloak Server comes with a Javascript library you can use to secure pure HTML/Javascript applications. It
works in the same way as other application adapters accept that your browser is driving the OAuth redirect protocol
rather than the server.
The
disadvantage of using this approach is that you end up having a non-confidential, public client. This can be mitigated
by registering valid redirect URLs. You are still vulnerable if somebody hijacks the IP/DNS name of your pure
HTML/Javascript application though.
startAsync
To use this adapter, you first must load and initialize the keycloak javascript library into your application.
Customer View Page
]]>
The above code will initialize the adapter and redirect you to your realm's login screen. You must fill in the
appropriate clientId, clientSecret, and realm options
based on how you created your application in your realm through the admin console. The init()
method can also take a success and error callback function as parameters.
After you login, your application will be able to make REST calls using bearer token authentication. Here's
an example pulled from the customer-portal-js example that comes with the distribution.
var loadData = function () {
document.getElementById('username').innerText = keycloak.username;
var url = 'http://localhost:8080/database/customers';
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Authorization', 'Bearer ' + keycloak.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var users = JSON.parse(req.responseText);
var html = '';
for (var i = 0; i < users.length; i++) {
html += '
' + users[i] + '
';
}
document.getElementById('customers').innerHTML = html;
console.log('finished loading data');
}
}
}
req.send();
};
var loadFailure = function () {
document.getElementById('customers').innerHTML = 'Failed to load data. Check console log';
};
var reloadData = function () {
keycloak.onValidAccessToken(loadData, loadFailure);
}
]]>
The loadData() method builds an HTTP request setting the Authorization
header to a bearer token. The keycloak.token points to the access token the browser obtained
when it logged you in. The loadFailure() method is invoked on a failure. The reloadData()
function calls keycloak.onValidAccessToken() passing in the loadData() and
loadFailure() callbacks. The keycloak.onValidAcessToken() method checks to
see if the access token hasn't expired. If it hasn't, and your oauth login returned a refresh token, this method
will refresh the access token. Finally, if successful, it will invoke the success callback, which in this case
is the loadData() method.