문제

나는 나머지 서버를 만들어서 그 사용하는 HTTPS 및으로 훌륭하게 작동합니다.여기에는 코드:

//Build a new Servlet Adapter.
ServletAdapter adapter=new ServletAdapter();
adapter.addInitParameter("com.sun.jersey.config.property.packages", "My.services");
adapter.addInitParameter(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, SecurityFilter.class.getName());
adapter.setContextPath("/");
adapter.setServletInstance(new ServletContainer());

//Configure SSL (See instructions at the top of this file on how these files are generated.)
SSLConfig ssl=new SSLConfig();
String keystoreFile=Main.class.getResource("resources/keystore_server.jks").toURI().getPath();
System.out.printf("Using keystore at: %s.",keystoreFile);
ssl.setKeyStoreFile(keystoreFile);
ssl.setKeyStorePass("asdfgh");

//Build the web server.
GrizzlyWebServer webServer=new GrizzlyWebServer(getPort(9999),".",true);

//Add the servlet.
webServer.addGrizzlyAdapter(adapter, new String[]{"/"});

//Set SSL
webServer.setSSLConfig(ssl);

//Start it up.
System.out.println(String.format("Jersey app started with WADL available at "
  + "%sapplication.wadl\n",
        "https://localhost:9999/"));
webServer.start();

지금,나는 그것에 도달하기 위해보십시오 Java:

SSLContext ctx=null;
try {
    ctx = SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e1) {
    e1.printStackTrace();
}
ClientConfig config=new DefaultClientConfig();
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(null,ctx));
WebResource service=Client.create(new DefaultClientConfig()).resource("https://localhost:9999/");

//Attempt to view the user's page.
try{
    service
        .path("user/"+username)
        .get(String.class);
}

을 얻을:

com.sun.jersey.api.client.ClientHandlerException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:128)
 at com.sun.jersey.api.client.Client.handle(Client.java:453)
 at com.sun.jersey.api.client.WebResource.handle(WebResource.java:557)
 at com.sun.jersey.api.client.WebResource.get(WebResource.java:179)

예에서는 웹에서 찾을 것 같아 나는 것을 설정해야 합 신뢰 저장소한 다음 설정의 일종 TrustManager.이처럼 보인다 많은 코드 및 설치에 대한 간단한 작은 프로젝트입니다.이 있는 쉬운 방법을 말한다.이 인증서를 신뢰하고 지점이다.인증서 파일입니까?

도움이 되었습니까?

해결책

당신이 말할 때는"거기 쉬운 방법이다.신뢰 이 인증서"정확히 무엇을,당신은 일을 추가하여 인증서를 Java 신뢰를 저장합니다.그리고 이것은 매우,매우 쉽게,그리고 거의 아무것도 할 필요가 내에서 클라이언트 응용 프로그램을 얻는 신뢰 저장소 인정되거나 활용된다.

클라이언트에서는 기계,어디에서 찾을 수 있 cacerts 파일을(기본 Java 신뢰를 저장하며,기본적으로 위치 <java-home>/lib/보안/인증/cacerts.

그런 다음,다음과 같이 입력합니다.

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to cacerts>

는 것이 가져오는 인증으로 귀하의 신뢰를 저장하고,이 후,당신의 클라이언트 응용 프로그램을 연결할 수 있습니다 당신의 회색을 띤 HTTPS 서버는 문제가 발생하지 않습니다.

지 않는 경우에 가져오려는 인증의 기본 신뢰 저장소--즉,당신은 그것을 사용할 수 있는 이 하나의 클라이언트에게 응용 프로그램이 있지만 아무것도에서 실행되는 JVM 에서는 기계--다음을 새로 만들 수 있습니다 신뢰를 저장하는 방법을 소개한 바 있습니다.전달하는 대신 키 도구 경로,기존의 기본 cacerts 파일을 전달 키 도구 경로를 당신의 새 신뢰 저장소 file:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to new trust store>

할 수 없습니다 설정 및 확인에 대한 새 암호 신뢰를 저장한 파일입니다.다음 시작할 때,당신의 클라이언트 응용 프로그램을 시작한 다음 매개변수:

java -Djavax.net.ssl.trustStore=<path to new trust store> -Djavax.net.ssl.trustStorePassword=<trust store password>

쉽게 치즈 맛이 나는 정말입니다.

다른 팁

고통스러운 길은 다음과 같습니다.

    SSLContext ctx = null;
    try {
        KeyStore trustStore;
        trustStore = KeyStore.getInstance("JKS");
        trustStore.load(new FileInputStream("C:\\truststore_client"),
                "asdfgh".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance("SunX509");
        tmf.init(trustStore);
        ctx = SSLContext.getInstance("SSL");
        ctx.init(null, tmf.getTrustManagers(), null);
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    ClientConfig config = new DefaultClientConfig();
    config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
            new HTTPSProperties(null, ctx));

    WebResource service = Client.create(config).resource(
            "https://localhost:9999/");
    service.addFilter(new HTTPBasicAuthFilter(username, password));

    // Attempt to view the user's page.
    try {
        service.path("user/" + username).get(String.class);
    } catch (Exception e) {
        e.printStackTrace();
    }

6 가지 다른 잡힌 예외를 사랑해야합니다 :). 코드를 조금 단순화하기위한 리팩토링이 확실히 있습니다. 그러나 저는 VM에서 Delfuego의 -D 옵션을 좋아합니다. 방금 설정할 수있는 javax.net.ssl.truststore 정적 속성이 있기를 바랍니다. 두 줄의 코드와 완료. 누구든지 그것이 어디에 있는지 아는 사람이 있습니까?

이것은 요청하기에는 너무 많을 수 있지만 이상적으로는 KeyTool이 사용되지 않습니다. 대신, TrustedStore는 코드에 의해 동적으로 생성되며 CERT는 런타임에 추가됩니다.

더 나은 대답이 있어야합니다.

명심해야 할 것은이 오류가 자체 서명 된 명품으로 인한 것이 아니라는 것입니다. 새로운 텐스트 CA CERT는 동일한 오류가 발생하지 않으며 올바른 일은이 중요한 보안 기능을 비활성화하지 않도록 적절한 루트 CERT로 서버를 업데이트하는 것입니다.

이것 좀 봐: http://code.google.com/p/resting/. 휴식을 사용하여 HTTPS REST Services를 소비 할 수있었습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top