Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically use Basic Authentication in WebView - JavaFX

I'm developing a JavaFX application and I'm trying to use WebView to access a web application. This web application has Basic Authentication and I want to submit the credentials programatically (don't want to prompt the user for his credentials, they're stored in the JavaFX application, I know the security implications about this approach).

The only link I found in google is this:

https://community.oracle.com/message/12518017

With no answers yet.

like image 489
Pablo Andrés Martínez Vargas Avatar asked Nov 23 '15 19:11

Pablo Andrés Martínez Vargas


2 Answers

We were actually trying the approach with using the Authenticator and it worked.

URI baseUri = URI.create("https://my.company.com/");
String username = "";
String password = "";

Authenticator.setDefault(new Authenticator() {

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        // only return our credentials for our URI
        if (baseUri.getHost().equals(getRequestingHost())) {
            return new PasswordAuthentication(username, password.toCharArray());
        }
        return null;
    }
});
like image 57
Dirk Fauth Avatar answered Nov 15 '22 11:11

Dirk Fauth


If you simply need to add an Authorization header, you can use the webEngine.setUserAgent() method to add any header you need.

For example, for basic authorization you would add the header like so:

webEngine.setUserAgent("foo\nAuthorization: Basic YourBase64EncodedCredentials");

A hacky solution I know, but I couldn't find another way to set a header.

like image 37
Brandon Thorne Avatar answered Nov 15 '22 12:11

Brandon Thorne