0

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;
}

2 Answers2

1

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"
Dilyano Senders
  • 199
  • 1
  • 9
  • check this link I think it contains your answer: https://stackoverflow.com/questions/496651/connecting-to-remote-url-which-requires-authentication-using-java/496707 – Dilyano Senders Feb 22 '19 at 14:29
  • Before I asked this question, I tried every way this link contains. Still, thank you! – Civoknats Feb 22 '19 at 14:39
0

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

Community
  • 1
  • 1
daniel
  • 2,665
  • 1
  • 8
  • 18