[Java lista] WebService a kliens oldal hitelesítésével

Komáromi Zoltán komaromi.zoltan at horticosoft.hu
2009. Már. 25., Sze, 17:22:21 CET


Most idáig jutottam, de valamiért még mindig nem megy. Ha esetleg 
megmondaná valaki, hogy mit bénáztam el, igen hálás lennék.
Jelenleg a szerver mindig 403-as hibát ad vissza, és a 
getLocalCertificates is mindig null-lal tér vissza. Ezért gondolom , 
hogy mégsem küldi el a kulcsot. Pedig a KeyManager metódusai 
meghívódnak, és helyes adatokat adnak vissza.

Csináltam KeyManagert:

public class AliasForcingKeyManager implements X509KeyManager {

  private final String alias;
  private final KeyStore keyStore;
  private final char[] password;

  public AliasForcingKeyManager(final String alias, final char[] passwd, 
final KeyStore keyStore) {
    this.alias = alias;
    this.keyStore = keyStore;
    this.password = passwd;
  }

  @Override
  public String chooseClientAlias(String[] keyType, Principal[] issuers, 
Socket socket) {
    AppLog.printDirect("ssl", getClass().getSimpleName() + ": 
chooseClientAlias [" + alias + "]", null, false);
    return this.alias;
  }

  @Override
  public String chooseServerAlias(String keyType, Principal[] issuers, 
Socket socket) {
    AppLog.printDirect("ssl", getClass().getSimpleName() + ": 
chooseServerAlias [" + alias + "]", null, false);
    return alias; //baseKM.chooseServerAlias(keyType, issuers, socket);
  }

  @Override
  public X509Certificate[] getCertificateChain(String alias) {
    AppLog.printDirect("ssl", getClass().getSimpleName() + ": 
chooseCertificateChain [" + alias + "]", null, false);
    try {
      Certificate[] ca = keyStore.getCertificateChain(alias);
      X509Certificate[] xa = new X509Certificate[ca.length];
      int cnt = 0;
      for (Certificate c : ca) {
        if (c instanceof X509Certificate) {
          xa[cnt++] = (X509Certificate) c;
        }
      }
      if (cnt < ca.length) {
        xa = Arrays.copyOf(xa, cnt);
      }
      AppLog.printDirect("ssl", getClass().getSimpleName() + ": " + xa, 
null, false);
      return xa; //baseKM.getCertificateChain(alias);
    } catch (KeyStoreException ex) {
      AppLog.printStack(ex, AliasForcingKeyManager.class, null, 
ex.getMessage());
      return new X509Certificate[0];
    }
  }

  @Override
  public String[] getClientAliases(String keyType, Principal[] issuers) {
    AppLog.printDirect("ssl", getClass().getSimpleName() + ": 
getClientAliases", null, false);
    /*
    try {
      List<String> al = new ArrayList<String>();

      for (Enumeration<String> en = keyStore.aliases(); 
en.hasMoreElements();) {
        al.add(en.nextElement());
      }
      String[] result = new String[al.size()];
      int i = 0;
      for (String a : al) {
        result[i] = a;
      }
      AppLog.printDirect("ssl", getClass().getSimpleName() + ": " + 
result, null, false);
      return result;
    } catch (KeyStoreException ex) {
      AppLog.printStack(ex, AliasForcingKeyManager.class, null, 
ex.getMessage());
      return new String[0];
    }
     */
    return new String[]{alias};
  }

  @Override
  public PrivateKey getPrivateKey(String alias) {
    AppLog.printDirect("ssl", getClass().getSimpleName() + ": 
getPrivateKey", null, false);
    try {
      PrivateKey result = (PrivateKey) keyStore.getKey(alias, password);
      AppLog.printDirect("ssl", getClass().getSimpleName() + ": " + 
result, null, false);
      return result;
    } catch (KeyStoreException ex) {
      AppLog.printStack(ex, AliasForcingKeyManager.class, null, 
ex.getMessage());
      return null;
    } catch (NoSuchAlgorithmException ex) {
      AppLog.printStack(ex, AliasForcingKeyManager.class, null, 
ex.getMessage());
      return null;
    } catch (UnrecoverableKeyException ex) {
      AppLog.printStack(ex, AliasForcingKeyManager.class, null, 
ex.getMessage());
      return null;
    }
  }

  @Override
  public String[] getServerAliases(String keyType, Principal[] issuers) {
    AppLog.printDirect("ssl", getClass().getSimpleName() + ": 
getserverAliases", null, false);
    return getClientAliases(keyType, issuers);
  }

Meg TrusManagert

public class UnauthenticatedClientTM implements TrustManager, 
X509TrustManager {

  @Override
  public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return null;
  }
 
  public boolean isServerTrusted(java.security.cert.X509Certificate[] 
certs) {
    return true;
  }
 
  public boolean isClientTrusted(java.security.cert.X509Certificate[] 
certs) {
    return true;
  }
 
  @Override
  public void checkServerTrusted(java.security.cert.X509Certificate[] 
certs, String authType) throws java.security.cert.CertificateException {
    return;
  }
 
  @Override
  public void checkClientTrusted(java.security.cert.X509Certificate[] 
certs, String authType) throws java.security.cert.CertificateException {
    return;
  }

}

És persze van egy Https kérést küldő osztály is:

public class Service {

  private static final String KEYSTORE_TYPE = "JKS";
 
  private static final char[] KEYSTORE_PASSWD = "passwd".toCharArray();

  private final static SSLSocketFactory createSSLFactory() {

    SSLContext ctx;
    SSLSocketFactory factory = null;
    try {
      ctx = SSLContext.getInstance("SSL");
      KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
      ks.load(new FileInputStream(AppProperties.getTransKeyDir() + 
"tomcat-keystore.jks"), KEYSTORE_PASSWD);

      ctx.init(new KeyManager[]{new AliasForcingKeyManager("tomcat", 
KEYSTORE_PASSWD, ks)},  new TrustManager[]{new 
UnauthenticatedClientTM()}, null);
      factory = ctx.getSocketFactory();
      return factory;
    } catch (Exception e) {
      AppLog.printStack(e, AbaqoosService.class, null, null);
      return null;
    }
  }

  private static final HttpsURLConnection createHttpsConnection(final 
String target_url) throws MalformedURLException, IOException {
    HttpsURLConnection conn = null;
    URL url = new URL(target_url);
    conn = (HttpsURLConnection) url.openConnection();
    SSLSocketFactory sf = createSSLFactory();
    AppLog.printDirect("ssl", "SSLFactory: " + 
(sf==null?"null":sf.toString()), null, false);
    conn.setSSLSocketFactory(sf);
    return conn;

  }
 
  public static final String doRequest(String targetURL, String charSet) 
throws IOException {
    return doRequest(targetURL, null, "GET", charSet);
  } 
 
  public static final String doRequest(String targetURL, Map<String, 
Object> params, String method, String charSet) throws IOException {
    String result = null;
    HttpURLConnection uconn;
    if (targetURL.startsWith("https://")){
      uconn = createHttpsConnection(targetURL);
    } else {
      URL url = new URL(targetURL);
      uconn = (HttpURLConnection)url.openConnection();     
    } 
    if (params != null) {
    StringBuffer psb = new StringBuffer();
    for (String pn : params.keySet()) {
      if (psb.length() > 0) {
        psb.append("&");
      }
      
psb.append(pn).append("=").append(URLEncoder.encode(params.get(pn).toString(), 
"ISO-8859-1"));
    }    

      uconn.setRequestMethod(method);     
      uconn.setUseCaches(false);
      uconn.setDefaultUseCaches(false);
      uconn.setDoInput(true);
      uconn.setDoOutput(true);
      uconn.setRequestProperty("Content-Type", 
"application/x-www-form-urlencoded");
      uconn.setRequestProperty("Content-Length", 
Integer.toString(psb.length()));
      OutputStream out = uconn.getOutputStream();
      out.write(psb.toString().trim().getBytes());
      out.flush();
      out.close();
    }
    //System.out.println(uconn.getResponseMessage());
    AppLog.printDirect("ssl", "Certificates:" + 
((HttpsURLConnection)uconn).getLocalCertificates(), null, false); // Ez 
mindig null
    InputStream is = uconn.getInputStream();
    try {
      int ulen = uconn.getContentLength();
      StringBuilder resp = new StringBuilder((ulen != -1) ? ulen : 100);
      BufferedReader br = new BufferedReader(new InputStreamReader(is, 
charSet));
      try {
        String l;
        while ((l = br.readLine()) != null) {
          resp.append(l.trim() + "\n");
        }
      } finally {
        br.close();
      }
      result = resp.toString();
    } finally {
      try {
        is.close();
      } catch (Throwable t) {
      }
    }
    return result;
  }

 ...
}

TomTo írta:
> 2009. március 20. dátummal Komáromi Zoltán ezt írta:
>   
>> Nálad ahogy nézem, a tiéd egy standalone program. Nálam meg
>> webalkalmazáshoz kell.
>>     
> Igen nekem erre volt szükségem anno. Azért ha találsz valami megoldást szerver 
> oldalra, az engem is érdekelne ;)
>
> Üdv,
> 	TomTo:)
>   
> ------------------------------------------------------------------------
>
>
> No virus found in this incoming message.
> Checked by AVG - www.avg.com 
> Version: 8.0.238 / Virus Database: 270.11.27/2021 - Release Date: 03/24/09 16:00:00
>
>   

--------- következő rész ---------
Egy csatolt HTML állomány át lett konvertálva...
URL: http://javagrund.hu/pipermail/javalist/attachments/20090325/e933a55f/attachment.html 


További információk a(z) Javalist levelezőlistáról