As part of a custom JS policy, I want to get data from an external API.
For example, I want to know if the weather in my city is good as part of my policy process.
It seems like fetch() is not available within a policy, is there any other way to do this ?
I want this call to be made every time the policy is applied.
An example of policy would be :
async function getWeather(location) {
let url = 'api-url/${location}/weather.json';
try {
let res = await fetch(url);
return await res.json();
} catch (error) {
console.log(error);
}
}
var context = $evaluation.getContext();
var identity = context.getIdentity();
var attributes = identity.getAttributes();
if (attributes.exists('location') === true) {
var location = attributes.getValue('location').asString(0);
if (getWeather(location) == "good") {
$evaluation.deny();
} else {
$evaluation.grant();
}
Based on this discussion: [keycloak-dev] Using plain javascript in javascript based policy
and a ticket they linked to, It appears that keycloak does not support standard built-in javascript functions that you would find in a web browser or in nodejs.
Unfortunately the ticket was closed…
Addendum 1:
Based on the newest documentation (today v15.0.0) you can no longer deploy js the same way. It now requires a Java jar file as well. I’m curious if the latest JS engine supports calls to external resources now.
Addendum 2:
It appears that they are still using the Nashorn JS engine in the latest version today. There is a ticket open to get rid of it. This engine does not support any web requests. Here is the ticket: https://issues.redhat.com/browse/KEYCLOAK-12755