Skip to main content

rustls_session/
rustls_session.rs

1//! Run with `cargo run --all-features --example rustls_session` command.
2//!
3//! To connect through browser, navigate to "https://localhost:3000" url.
4//!
5//! Shows the TLS connection information that is available to handlers: the
6//! SNI server name, the negotiated ALPN protocol, and client certificates.
7
8use axum::{routing::get, Extension, Router};
9use axum_server::{tls::TlsInfo, tls_rustls::RustlsConfig};
10use std::{net::SocketAddr, sync::Arc};
11
12#[tokio::main]
13async fn main() {
14    let app = Router::new().route("/", get(handler));
15
16    let config = RustlsConfig::from_pem_file(
17        "examples/self-signed-certs/cert.pem",
18        "examples/self-signed-certs/key.pem",
19    )
20    .await
21    .unwrap();
22
23    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
24
25    println!("listening on {}", addr);
26
27    axum_server::bind_rustls(addr, config)
28        .serve(app.into_make_service())
29        .await
30        .unwrap();
31}
32
33async fn handler(Extension(info): Extension<Arc<TlsInfo>>) -> String {
34    format!(
35        "server name: {:?}\nalpn: {:?}\nclient certificates: {}",
36        info.server_name,
37        info.alpn_protocol.as_deref().map(String::from_utf8_lossy),
38        info.peer_certificates.len(),
39    )
40}