Civoknats
Civoknats

Reputation: 11

Connect to remote URL with domain, username and pw

Heys guys, following problem here: I have a username which looks like "ABCD\michael" and a password which looks like "password!6789". "ABCD" in this case is the domain.

With the following code, im getting 401 unauthorized as a response code. I suspect, that the doublebackslashes are not being converted to a single backslash prior the base64 encoding. Or am I using the domain in a wrong way?

I need help to get this working. Help would be appreciated.

Thank you in advance!

public int getMeTheResponseCodeOfURL(final URL url) {
    HttpURLConnection httpUrlConnection = null;
    int statusCode = 0;
    String userName = "ABCD\\michael";
    String userPass = "password!6789";
    String UserAndPass = userName + ":" + userPass;
    String userPassBase64 = Base64.getEncoder().encodeToString(UserAndPass.getBytes());

    try {
        httpUrlConnection = (HttpURLConnection) url.openConnection();
        httpUrlConnection.setRequestProperty("Authorization", "Basic " + userPassBase64);
        httpUrlConnection.connect();
        statusCode = httpUrlConnection.getResponseCode();

    } catch (final IOException e) {
        this.log.error("IO Exception! Errormessage: " + e);
    }
    return statusCode;
}

Upvotes: 1

Views: 888

Answers (2)

daniel
daniel

Reputation: 3278

Another thing to try is using UserAndPass.getBytes("UTF-8"), though your UserAndPass string only contains US-ASCII characters - so it may not matter - but remember that String.getBytes() [1] (with no args) encodes the string bytes using the default platform charset, which may not always be what you want. It is rarely a good idea to depend on the default charset.

Also if "ABCD" is the authentication realm then it might no need to be part of the UserAndPass string - see RFC 7617 [2]

[1] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#getBytes()

[2] https://www.rfc-editor.org/rfc/rfc7617

Upvotes: 0

Dilyano Senders
Dilyano Senders

Reputation: 199

Could you try and replace the \ sign with %5C This is the encode code for the slash. So your username will look like this:

String userName = "ABCD%5Cmichael"

Upvotes: 1

Related Questions