2011-04-21 18 views
10

El problema aquí es consumir un recurso web que tiene autenticación NTLM mientras se utiliza Apache HttpClient en el lado del cliente. El problema que estoy teniendo es forzar al cliente a usar la autenticación NTLM. aquí hay un código sapmle.Apache HttpClient 4.1.1 Autenticación NTLM no SPNEGO

DefaultHttpClient httpclient = new DefaultHttpClient(); 
httpclient.getAuthSchemes().register("ntlm",new NTLMSchemeFactory()); 
NTCredentials creds = new NTCredentials("_myUSer_","_myPass_","_myWorkstation_","_myDomain_"); 
httpclient.getCredentialsProvider().setCredentials(new AuthScope("serverName",80), creds); 
List<String> authpref = new ArrayList<String>(); 
authpref.add(AuthPolicy.NTLM); 
httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); 
HttpHost target = new HttpHost("serverName", 80, "http"); 
HttpGet httpget = new HttpGet("webResource"); 
HttpContext localContext = new BasicHttpContext(); 
HttpResponse response = httpclient.execute(target, httpget, localContext); 

Aquí está el error de Java:

org.apache.http.client.protocol.RequestTargetAuthentication process 
SEVERE: Authentication error: Invalid name provided (Mechanism level: Could not load configuration file C:\WINDOWS\krb5.ini (The system cannot find the file specified)) 

La respuesta del servidor Web es un 401.

¿Alguna idea sobre por qué la política de autenticación no está configurada correctamente? ¿Me falta algo en el código?

+1

he encontrado un problema con mi código y es que el AuthScope debe apuntar a su proxy y no su objetivo, que se deshizo de los errores en los que estaba tratando de usar Kerberos en lugar de NTLM , pero todavía recibo un 401 del servidor, ¿alguna idea sobre la combinación correcta de nombre de usuario/contraseña/dominio? – Kelly

+1

HttpClient necesita ser actualizado verifique mi publicación [http://stackoverflow.com/questions/5917356/httpclient-4-1-1-returns-401-when-authenticating-with-ntlm-browsers-work-fine/20047880# 20047880] [1] [1]: http://stackoverflow.com/questions/5917356/httpclient-4-1-1-returns-401-when-authenticating-with-ntlm-browsers-work -fine/20047880 # 20047880 –

Respuesta

0

Creo que esto se debe a un defecto, consulte here.

5

Tengo una situación similar y sospecho que está configurando el parámetro incorrecto: AuthPNames.PROXY_AUTH_PREF. Yo uso AuthPNames.TARGET_AUTH_PREF y todo parece funcionar bien.

2

Aquí está mi solución a este problema: Y "evandongen" es correcto.

Tenga en cuenta el uso del URIBuilder.

String username = "uid"; 
String pwd = "pwd"; 
String servername = "www.someserver.com"; 
String workstation = "myworkstation"; 
String domain = "somedomain"; 
String relativeurl = "/util/myservice.asmx"; 

String oldimagePath = "\\mypath\\image.jpg"; 

DefaultHttpClient httpclient = new DefaultHttpClient(); 

try { 
    httpclient.getAuthSchemes().register("ntlm",new NTLMSchemeFactory()); 
    NTCredentials creds = new NTCredentials(username,pwd,workstation,domain); 

     httpclient.getCredentialsProvider().setCredentials(new AuthScope(servername,80), creds); 

     List authpref = new ArrayList(); 

     authpref.add(AuthPolicy.NTLM); 

     URIBuilder builder = new URIBuilder(); 
     builder.setScheme("http") 
      .setHost(servername) 
      .setPath(relativeurl + "/DeleteImage") 
      .setParameter("imagePath", oldimagePath); 
     URI uri = builder.build(); 

     httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); 
     HttpHost target = new HttpHost(servicename, 80, "http"); 
     HttpGet httpget = new HttpGet(uri); 

     HttpContext localContext = new BasicHttpContext(); 

     HttpResponse response1 = httpclient.execute(target, httpget, localContext); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(response1.getEntity().getContent())); 

     String line = reader.readLine(); 
     while (line != null) 
     { 
      System.out.println(line); 
      line = reader.readLine(); 
     } 

} catch (Exception e) { 
    System.out.println("Exception:"+e.toString()); 
} finally { 
    // End 
} 
0

HttpClient no funcionó para mí pero el siguiente fragmento lo hizo. Referencia - http://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html

public static String getResponse(String url, String userName, String password) throws IOException { 
    Authenticator.setDefault(new Authenticator() { 
     @Override 
     public PasswordAuthentication getPasswordAuthentication() { 
     System.out.println(getRequestingScheme() + " authentication"); 
     return new PasswordAuthentication(userName, password.toCharArray()); 
     } 
    }); 

    URL urlRequest = new URL(url); 
    HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection(); 
    conn.setDoOutput(true); 
    conn.setDoInput(true); 
    conn.setRequestMethod("GET"); 

    StringBuilder response = new StringBuilder(); 
    InputStream stream = conn.getInputStream(); 
    BufferedReader in = new BufferedReader(new InputStreamReader(stream)); 
    String str = ""; 
    while ((str = in.readLine()) != null) { 
     response.append(str); 
    } 
    in.close(); 

    return response.toString(); 
    } 
Cuestiones relacionadas