SeleniumHQ / htmlunit-driver

WebDriver compatible driver for HtmlUnit headless browser.
Apache License 2.0
255 stars 86 forks source link

Implement HasAuthentication to be able to use authentication #138

Open TareqK opened 10 months ago

TareqK commented 10 months ago

So after some debugging on a project, i found out that the driver doesn't implement HasAuthentication, which means that using basic authentication with selenide does not work - and might not work with mainline selenium(didn't test that). In all cases, implementing HasAuthentication solves this problem. I have a really dumb internal implementation, but having this built in would be nice.

TareqK commented 10 months ago

Dumb workaround for basic authentication if someone is looking

public  class HtmlUnitDriverWithAuth extends HtmlUnitDriver implements HasAuthentication {

        public HtmlUnitDriverWithAuth() {
            super();
        }

        public HtmlUnitDriverWithAuth(BrowserVersion version) {
            super(version);
        }

        public HtmlUnitDriverWithAuth(boolean enableJavascript) {
            super(enableJavascript);
        }

        public HtmlUnitDriverWithAuth(BrowserVersion version, boolean enableJavascript) {
            super(version, enableJavascript);
        }

        public HtmlUnitDriverWithAuth(Capabilities capabilities) {
            super(capabilities);
        }

        public HtmlUnitDriverWithAuth(Capabilities desiredCapabilities, Capabilities requiredCapabilities) {
            super(desiredCapabilities, requiredCapabilities);
        }

        @Override
        public void register(Predicate<URI> whenThisMatches, Supplier<Credentials> useTheseCredentials) {
            Require.nonNull("Check to use to see how we should authenticate", whenThisMatches);
            Require.nonNull("Credentials to use when authenticating", useTheseCredentials);
            Credentials credentials = useTheseCredentials.get();
            if (credentials instanceof UsernameAndPassword usernameAndPassword) {
                String username = usernameAndPassword.username();
                String password = usernameAndPassword.password();
                String credsString = new StringBuilder(username).append(":").append(password).toString();
                String base64encodedUsernameAndPassword = new String(Base64.getEncoder().encode(credsString.getBytes()));
                this.getWebClient().addRequestHeader("Authorization", "Basic " + base64encodedUsernameAndPassword);
            }
        }

    }