Authentication for URLClassLoader

154 views Asked by At

A project I'm working on requires a URLClassLoader, which is supposed to load a .jar file from the Internet that is protected by very basic authentication. To access this jar file, one must send a GET request with an Authorization header to a specific URL.

By default, the URLClassLoader just sends the GET request, and I'm having some trouble getting it to send the headers as well.

On another StackOverflow Thread I found that I am supposed to pass a custom URLStreamHandler in the URLClassLoader's constructor, which is what I tried doing: I extended URLClassLoader in a custom class, calling this constructor super(new URL[]{url}, parent, protocol -> new LicensedURLStreamHandler(token));, where LicensedURLStreamHandler is

import java.io.IOException;
import java.net.*;

public class LicensedURLStreamHandler extends URLStreamHandler {

    private final String token;

    public LicensedURLStreamHandler(String token) {
        this.token = token;
    }

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        URL url = new URL(u.toString());
        JarURLConnection con = (JarURLConnection) url.openConnection();

        con.setRequestProperty("Authorization", token);
        con.setRequestProperty("Accept", "application/octet-stream");

        return con;
    }
}

However, on the server side, both headers appear not to have been included, because the only ones that are present are Accept:[text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2] Connection:[keep-alive] User-Agent:[Java/1.8.0_362]

In essence, the server receives the request without the headers I added in the LicensedURLStreamHandler. I don't really know how to fix this, and the already scarce documentation on the subject hasn't helped me.

0

There are 0 answers