-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSSLExample.java
More file actions
67 lines (59 loc) · 2.73 KB
/
SSLExample.java
File metadata and controls
67 lines (59 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package examples.ssl;
import com.vtence.molecule.Response;
import com.vtence.molecule.WebServer;
import com.vtence.molecule.middlewares.ApacheCommonLogger;
import com.vtence.molecule.middlewares.ForceSSL;
import examples.files.Logging;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.time.Clock;
import java.util.Locale;
import static com.vtence.molecule.http.HttpStatus.NOT_FOUND;
import static com.vtence.molecule.testing.ResourceLocator.locateOnClasspath;
/**
* <p>
* In this example we create and start an HTTPS server. We use a JKS keystore that contains our
* self-signed certificate. Alongside the secure server we start a insecure HTTP server, which redirects
* to the secure server.
* </p>
* <p>
* To generate the self-signed certificate using an 2048 bits RSA key pair, use the following command:
* <br>
* <code>keytool -genkey -keyalg RSA -alias <i>key alias</i> -keystore <i>keystore file</i>
* -storepass <i>store password</i> -keysize 2048</code>
* </p>
*/
public class SSLExample {
public void redirect(WebServer insecure, WebServer secure) throws IOException {
// Redirect users to the secure connection
insecure.add(new ForceSSL().redirectTo(secure.uri().getAuthority()))
.start(request -> Response.of(NOT_FOUND)
.done("Nothing here!"));
}
public void run(WebServer server) throws IOException, GeneralSecurityException {
// That's our JKS keystore containing our certificate
File keyStore = locateOnClasspath("ssl/keystore");
// The password to open the keystore
String keyStorePassword = "password";
// The password to use the key
String keyPassword = "password";
// We enable TLS with our key store password and key password
server.enableSSL(keyStore, keyStorePassword, keyPassword)
// Add HSTS security headers
.add(new ForceSSL())
.add(new ApacheCommonLogger(Logging.toConsole(), Clock.systemDefaultZone(), Locale.getDefault()))
// We a render a simple text to let our user know she is on a secure channel
.start(request -> Response.ok().done("You are on a secure channel"));
}
public static void main(String[] args) throws IOException, GeneralSecurityException {
SSLExample example = new SSLExample();
// Run the insecure web server on port 8080
WebServer insecure = WebServer.create(8080);
// Run the secure (SSL) web server on port 8443
WebServer secure = WebServer.create(8443);
example.redirect(insecure, secure);
example.run(secure);
System.out.println("Access at " + insecure.uri());
}
}