Http URL-соединение сначала запрашивает согласование, а затем базовая схема аутентификации для того же URL - PullRequest
0 голосов
/ 16 января 2019

Я действительно новичок в Java-кодировании. пожалуйста, посмотрите на мою проблему и помогите мне решить. я пытался получить данные с внутреннего веб-сервера, где веб-страница сначала запрашивала «согласовать», а затем «базовую» аутентификацию для того же сайта.

Я попытался пройти базовую аутентификацию с использованием цикла создания if, но если условие всегда находится в состоянии False и выполняется только цикл else. А также надоело пройти базовую аутентификацию в шапке, но не повезло.

класс аутентификации для передачи учетных данных NTLM

public class RunHttpSpnego {

static final String kuser = "user"; // your account name
static final String kpass = "pass"; // your password for the account

static class MyAuthenticator extends Authenticator {
    public PasswordAuthentication getPasswordAuthentication() {
        // I haven't checked getRequestingScheme() here, since for NTLM
        // and Negotiate, the usrname and password are all the same.
        System.err.println("Feeding username and password for " + getRequestingScheme());
        System.err.println("Feeding username and password for " + getRequestorType()+"URL: "+ getRequestingURL());
       if (getRequestingScheme().contains("Negotiate ")) {
            return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
        else {
            String name = "test_dom\\user";
            String password = "pass";
            System.err.println("Block 1");
            return (new PasswordAuthentication(name, password.toCharArray()));

        }
      }
}

public static void main(String[] args) throws Exception {
        // Key to provide internal handshake 
    System.setProperty("javax.net.ssl.trustStore", "InternalAndExternalTrustStore.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "pass");

    Authenticator.setDefault(new MyAuthenticator());
    URL url = new URL("https://test_dom.com/users/directory.json");

    HttpURLConnection conn = (HttpURLConnection)url.openConnection();

          // Verified by passing basic authentication but no luck 
    //String auth = getAuthorization("test_dom\\user", "pass");
        //conn.setRequestProperty ("Authorization", "Basic " + auth);
    conn.setRequestProperty ("Content-Type", "application/json");

    InputStream ins = conn.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
    String str;
    while((str = reader.readLine()) != null)
        System.out.println(str);
}

private static String getAuthorization(String user, String password)
{
    try 
    {
        return getBase64((user + ":" + password).getBytes("UTF-8"));
    }
    catch (UnsupportedEncodingException e)
    {
        // Not thrown
    }

    return "";
}

private static String getBase64(byte[] buffer){

..... }

}

Вот ошибка, которую я получаю с кодом выше:

Feeding username and password for Negotiate
Feeding username and password for SERVERURL: 
https://sentry.test_dom.com/SSO/redirect?redirect_uri=https%3A%2F%test_dom.com%3A443%2Fusers%2Fdirectory.json&client_id=https%3A%2F%2Ftest_dom.com%3A443&scope=openid&response_type=id_token&nonce=7e0f7ed81feec2cbf0495c564edd307118ffccd295465465464h615877275f795eded852825&sentry_handler_version=OpenIdConnectApacheMod-1.1-1
Block 1
Feeding username and password for basic
Feeding username and password for SERVERURL: 
https://sentry.test_dom.com/SSO/redirect?redirect_uri=https%3A%2F%2Ftest_dom.com%3A443%2Fusers%2Fdirectory.json&client_id=https%3A%2F%2Ftest_dom.com%3A443&scope=openid&response_type=id_token&nonce=7e0f7ed81feec2cbf0495c564edd307118ffccd295465465464h615877275f795eded852825&sentry_handler_version=OpenIdConnectApacheMod-1.1-1
Block 1
Exception in thread "main" java.net.ProtocolException: Server redirected too many  times (20)
    at 
sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at RunHttpSpnego.main(RunHttpSpnego.java:51)
...