Javascript-based policy send request to external API

Hello,

I’m trying to write a javascript policy to send a request to an external API to validate the authorization

I tested with this code:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8000/authorize?resourceId=' + $evaluation.context.get('resourceId'), true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            $evaluation.grant();
        } else {
            $evaluation.deny();
        }
    }
};
xhr.send();

but in keycloak logs I get:

“Failed to evaluate permissions”
Caused by: java.lang.RuntimeException: Error evaluating JS Policy [External Validation]
Caused by: java.lang.RuntimeException: javax.script.ScriptException: ReferenceError: “XMLHttpRequest” is not defined in at line number 1

I did some research and found that the engine used to evaluate javascript is Nashron JS and it does not have http capabilities through XMLHttpRequest (DOM API)

Does that mean what i’m trying to accomplish here is impossible, or are there other workarounds for this?

You can call java methods when using Nashorn. See the HttpURLConnection class, or just use something like this:

function httpGet(url){
    var connection = new java.net.URL(url).openConnection();
    connection.requestMethod = "GET";
    var d = read(connection.inputStream);
    return {data : d, statusCode : connection.responseCode};
}
1 Like

Thank you for you response, this is my first time encountering Nashron I had no idea we could use java methods.

I have another question please, what is the best way to develop and debug these Javascript policies?
because I have to write the scripts and create the jar then copy it to the providers folder on the container and build and restart the container each time I make a change which is not optimal at all