2013-07-11 4 views
2

В настоящее время я работаю над Java-проектом, и я не могу заставить работать аутентификатор электронной почты. Я попытался использовать веб-сайт Apache, но это не помогло. У меня есть сайт, для которого требуется аутентификация дайджеста HTTP.Apache Http Digest Аутентификация с использованием Java

 DefaultHttpClient httpclient = new DefaultHttpClient(); 
     String hostUrl = "http://somewebsite.com"; 
     String postUrl = "http://somewebsite.com/request"; 
     HttpPost httpPost = new HttpPost(postUrl); 
     String username = "hello"; 
     String password = "world"; 
     HttpHost targetHost = new HttpHost(hostUrl); 

     httpclient.getCredentialsProvider().setCredentials(
       new AuthScope(hostUrl, AuthScope.ANY_PORT), 
       new UsernamePasswordCredentials(username, password)); 

     AuthCache authCache = new BasicAuthCache(); 

     DigestScheme digestAuth = new DigestScheme(); 

     digestAuth.overrideParamter("realm", "some realm"); 

     digestAuth.overrideParamter("nonce", "whatever"); 
     authCache.put(targetHost, digestAuth); 

     BasicHttpContext localcontext = new BasicHttpContext(); 
     localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 

     // List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 
     // nvps.add(new BasicNameValuePair("username", "[email protected]")); 
     // nvps.add(new BasicNameValuePair("password", "example")); 
     // httpPost.setEntity(new UrlEncodedFormEntity(nvps)); 
     HttpResponse response2 = httpclient.execute(httpPost); 
+0

любое решение для этого? –

ответ

0

Попробуйте этот код из Apache:

public static void main(String[] args) throws Exception { 
      HttpClient client = new HttpClient(); 
      client.getState().setCredentials(
       new AuthScope("myhost", 80, "myrealm"), 
       new UsernamePasswordCredentials("username", "password")); 
      // Suppose the site supports several authetication schemes: NTLM and Basic 
      // Basic authetication is considered inherently insecure. Hence, NTLM authentication 
      // is used per default 

      // This is to make HttpClient pick the Basic authentication scheme over NTLM & Digest 
      List authPrefs = new ArrayList(3); 
      authPrefs.add(AuthPolicy.BASIC); 
      authPrefs.add(AuthPolicy.NTLM); 
      authPrefs.add(AuthPolicy.DIGEST); 
      client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authrefs); 

      GetMethod httpget = new GetMethod("http://myhost/protected/auth-required.html"); 

      try { 
       int status = client.executeMethod(httpget); 
       // print the status and response 
       System.out.println(httpget.getStatusLine()); 
       System.out.println(httpget.getResponseBodyAsString()); 
      } finally { 
       // release any connection resources used by the method 
       httpget.releaseConnection(); 
      }    
     } 
+0

Это не работает. GetMethod больше не существует. – user2351234

1

попробовать этот код из апача HTTPClient 4.3.3

final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); 
    final CredentialsProvider credsProvider = new BasicCredentialsProvider(); 
    credsProvider.setCredentials(AuthScope.ANY, 
      new UsernamePasswordCredentials(user, password)); 

    final AuthCache authCache = new BasicAuthCache(); 
    DigestScheme digestAuth = new DigestScheme(); 
    digestAuth.overrideParamter("realm", "some-realm"); 
    digestAuth.overrideParamter("nonce", "whatever"); 
    authCache.put(targetHost, digestAuth); 

    // Add AuthCache to the execution context 
    HttpClientContext context = HttpClientContext.create(); 
    context.setAuthCache(authCache); 
HttpGet httpget = new HttpGet("/"); 
CloseableHttpResponse response = httpclient.execute(targetHost , httpget, context); 

Пожалуйста, вы можете дать мне сайт, который требует HTTP дайджест-проверки подлинности?

+0

Вы нашли какой-либо интернет-сервис для проверки своих вещей? –

+0

Я использую http://httpbin.org. Для проверки есть конечная точка аутстата дайджеста. Но я все еще получаю обратно 401, используя код выше. Этот фрагмент работает для всех, кто использует Digest Auth? – jamiltz

2

Этот код работает для меня довольно хорошо:

protected static void downloadDigest(URL url, FileOutputStream fos) 
    throws IOException { 
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); 
    CloseableHttpClient httpClient = HttpClients.createDefault(); 
    HttpClientContext context = HttpClientContext.create(); 

    String credential = url.getUserInfo(); 
    if (credential != null) { 
    String user = credential.split(":")[0]; 
    String password = credential.split(":")[1]; 

    CredentialsProvider credsProvider = new BasicCredentialsProvider(); 
    credsProvider.setCredentials(AuthScope.ANY, 
     new UsernamePasswordCredentials(user, password)); 
    AuthCache authCache = new BasicAuthCache(); 
    DigestScheme digestScheme = new DigestScheme(); 
    authCache.put(targetHost, digestScheme); 

    context.setCredentialsProvider(credsProvider); 
    context.setAuthCache(authCache); 
    } 

    HttpGet httpget = new HttpGet(url.getPath()); 

    CloseableHttpResponse response = httpClient.execute(targetHost, httpget, context); 

    try { 
    ReadableByteChannel rbc = Channels.newChannel(response.getEntity().getContent()); 
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 
    } finally { 
    response.close(); 
    } 
}