java - 在Jetty服务器中如何获取需要客户端认证时使用的客户端证书?

标签 java ssl embedded-jetty authentication

设置请求客户端身份验证的嵌入式 Jetty 服务器非常容易:只需添加以下语句 SslContextFactory.setNeedClientAuth(true); 配置服务器时到 ssl 上下文。任何在服务器的信任库中拥有其证书的客户端都能够与服务器建立 TLS 连接。

但是我需要知道所有可能的可信客户端中的哪个客户端当前正在发出请求;换句话说,我需要知道此连接中使用的客户端证书,特别是在处理程序中。有谁知道如何访问此证书或者是否有可能?

最佳答案

2019 年 8 月更新:适用于 Jetty 9.4.20.v20190813 版本。

证书被添加到 Request对象(例如 HttpServletRequest ),由 HttpConfiguration Customizer .

具体来说,SecureRequestCustomizer .

使用它的代码如下(向下滚动)...

Server server = new Server();

// === HTTP Configuration ===
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
http_config.setRequestHeaderSize(8192);
http_config.setResponseHeaderSize(8192);
http_config.setSendServerVersion(true);
http_config.setSendDateHeader(false);

// === Add HTTP Connector ===
ServerConnector http = new ServerConnector(server,
    new HttpConnectionFactory(http_config));
http.setPort(8080);
http.setIdleTimeout(30000);
server.addConnector(http);

// === Configure SSL KeyStore, TrustStore, and Ciphers ===
SslContextFactory sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath("/path/to/keystore");
sslContextFactory.setKeyStorePassword("changeme");
sslContextFactory.setKeyManagerPassword("changeme");
sslContextFactory.setTrustStorePath("/path/to/truststore");
sslContextFactory.setTrustStorePassword("changeme");
// OPTIONAL - for client certificate auth (both are not needed)
// sslContextFactory.getWantClientAuth(true)
// sslContextFactory.setNeedClientAuth(true)

// === SSL HTTP Configuration ===
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer()); // <-- HERE

// == Add SSL Connector ===
ServerConnector sslConnector = new ServerConnector(server,
    new SslConnectionFactory(sslContextFactory,"http/1.1"),
    new HttpConnectionFactory(https_config));
sslConnector.setPort(8443);
server.addConnector(sslConnector);

有了这个 SecureRequestCustomizer,您可以使用以下属性名称从 HttpServletRequest.getAttribute(String) 调用访问有关 SSL 连接的各种部分。

javax.servlet.request.X509Certificate

java.security.cert.X509Certificate 的数组[]

javax.servlet.request.cipher_suite

密码套件的字符串名称。 (与从 javax.net.ssl.SSLSession.getCipherSuite() 返回的相同)

javax.servlet.request.key_size

使用的 key 长度的整数

javax.servlet.request.ssl_session_id

Activity SSL session ID 的字符串表示(十六进制)

关于java - 在Jetty服务器中如何获取需要客户端认证时使用的客户端证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20056304/

相关文章:

jersey - 如何在 JAX-RS 客户端中使用 CDI

ios - 如果启用了 SSL 代理,为什么 Charles 代理上的 https 请求会失败

android - 使用改造调用添加自签名证书

java - InetAddresses 的 isInetAddress 和 isUriInetAddress 的区别

java - 初始化父类(super class)成员的正确方法是什么?

java - 从 PositiveSSL 证书创建私钥

java - 没有 JKS 的嵌入式 Jetty 上的 TLS

java - RESTEasy UnavailableException HttpServletDispatcher

java - 如何从 ObjectInputStream 读取所有对象

java - 翻译简单的C代码