How to programatically use Basic Authentication in WebView - JavaFX
Asked Answered
W

2

7

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.

Workroom answered 23/11, 2015 at 19:35 Comment(0)
P
5

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;
    }
});
Pontonier answered 28/2, 2017 at 9:55 Comment(1)
Works like a charm together with JavaFX WebView! :-)Centering
P
3

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.

Party answered 30/6, 2017 at 19:25 Comment(1)
Hacky, but you're not alone in using it: twitter.com/CodingFabian/status/524942996748652544Kurus

© 2022 - 2024 — McMap. All rights reserved.