1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package groovyx.net.http;
23
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.MalformedURLException;
27 import java.net.URL;
28 import java.security.GeneralSecurityException;
29 import java.security.KeyStore;
30
31 import org.apache.http.auth.AuthScope;
32 import org.apache.http.auth.UsernamePasswordCredentials;
33 import org.apache.http.conn.scheme.Scheme;
34 import org.apache.http.conn.ssl.SSLSocketFactory;
35
36
37
38
39
40
41
42 public class AuthConfig {
43 protected HTTPBuilder builder;
44 public AuthConfig( HTTPBuilder builder ) {
45 this.builder = builder;
46 }
47
48
49
50
51
52
53
54
55
56 public void basic( String user, String pass ) {
57 URL url = (URL)builder.getURL();
58 if ( url == null ) throw new IllegalStateException( "a default URL must be set" );
59 this.basic( url.getHost(), url.getPort(), user, pass );
60 }
61
62
63
64
65
66
67
68
69 public void basic( String host, int port, String user, String pass ) {
70 builder.getClient().getCredentialsProvider().setCredentials(
71 new AuthScope( host, port ),
72 new UsernamePasswordCredentials( user, pass )
73 );
74 }
75
76
77
78
79
80
81 public void certificate( String certURL, String password )
82 throws GeneralSecurityException, MalformedURLException, IOException {
83
84 KeyStore keyStore = KeyStore.getInstance( KeyStore.getDefaultType() );
85 InputStream jksStream = new URL(certURL).openStream();
86 try {
87 keyStore.load( jksStream, password.toCharArray() );
88 } finally { jksStream.close(); }
89
90 SSLSocketFactory ssl = new SSLSocketFactory(keyStore, password);
91 ssl.setHostnameVerifier( SSLSocketFactory.STRICT_HOSTNAME_VERIFIER );
92
93 builder.getClient().getConnectionManager().getSchemeRegistry()
94 .register( new Scheme("https", ssl, 443) );
95 }
96 }