如何在 Axum 上使用 ssl

问题描述 投票:0回答:1

我有一个功能:

async fn start_http_server(
    cors: CorsLayer,
) -> Result<(), Box<dyn Error + Send + Sync>> {
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8000").await?;
    let app = Router::new()
        .nest("/", router())
        .layer(cors);
    axum::serve(listener, app).await?;
    Ok(())
}

它在 http 上工作得很好,但是当我尝试让它与自签名证书一起工作时,问题就出现了。我尝试通过 axum_server 来完成此操作,例如:

let config = RustlsConfig::from_pem_file(
        "examples/self-signed-certs/cert.pem",
        "examples/self-signed-certs/key.pem",
    )
    .await
    .unwrap();

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    println!("listening on {}", addr);
    axum_server::bind_rustls(addr, config)
        .serve(app.into_make_service())
        .await
        .unwrap();

但是没有找到::bind_rustles。所有教程都涉及同一主题(未找到)。我不知何故到了我不明白它如何不给出错误的地步,但它也不起作用):

async fn start_https_server(
    cors: CorsLayer,
) -> Result<(), Box<dyn Error + Send + Sync>> {
    let tls_config = RustlsConfig::from_pem_file("cert.pem", "key.pem").await?;
    println!("tls_config: {:?}",tls_config);
    let app = Router::new()
        .nest("/", router())
        .layer(cors);
    let ip = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
    let port = 8000;
    let addr = SocketAddr::new(ip, port);
    bind_rustls(addr, tls_config)
        .serve(app.into_make_service())
        .await?;
    Ok(())
}

打印!不输出任何内容。请帮我解决问题。我们和一位同事坐在一起在本地网络上写作,我把证书扔给了他。 cors 已配置:

  let cors = CorsLayer::new()
        // .allow_origin(HeaderValue::from_static("*"))cors_link
        .allow_origin(cors_origin)
        .allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE,Method::OPTIONS])
        .allow_credentials(false)
        .allow_headers([
            AUTHORIZATION,
            ACCEPT,
            CONTENT_TYPE,
            HeaderName::from_static("accept-ch"),           
            HeaderName::from_static("sec-ch-ua"),           
            HeaderName::from_static("sec-ch-ua-mobile"),     
            HeaderName::from_static("sec-ch-ua-platform"),   
            HeaderName::from_static("max-touch-points"),    
            HeaderName::from_static("location"),
        ])
        .allow_credentials(true);

我只需要拿到饼干..

ssl rust rust-tokio rust-axum
1个回答
0
投票

一般来说,在这种情况下,它是有效的,如何做得更好 - 你会弄清楚的)该方法正在起作用

async fn start_https_server(
    cors: CorsLayer,
) -> Result<(), Box<dyn Error + Send + Sync>> {
    let cert_file = File::open("src/certs/cert.pem")?;
    let key_file = File::open("src/certs/key.pem")?;
    let mut cert_reader = BufReader::new(cert_file);
    let mut key_reader = BufReader::new(key_file);
    let certs = certs(&mut cert_reader)
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .map(|cert| cert.into_owned())
        .collect::<Vec<_>>();
    let keys: Vec<_> = pkcs8_private_keys(&mut key_reader)
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .map(|key| key)
        .collect();
    let keys = keys
        .into_iter()
        .map(|key| PrivateKeyDer::from(key))
        .collect::<Vec<_>>();
    let tls_config = ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(certs.clone(), keys[0].clone_key())?;
    let app = Router::new()
        .nest("/", router())
        .layer(cors);
    let ip = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
    let port = 8000;
    let addr = SocketAddr::new(ip, port);
    let rustls_config = RustlsConfig::from_config(Arc::new(tls_config));
    if let Err(e) = bind_rustls(addr, rustls_config)
        .serve(app.into_make_service())
        .await
    {
        eprintln!("Error while serving HTTPS: {:?}", e);
        return Err(Box::new(e));
    }
    Ok(())
}

也为了让它更容易:

tokio-rustls = "0.26.0"
rustls-pemfile = "2.2.0"
axum-server = { version = "0.7.1",features = ["tls-rustls-no-provider"] }
use std::fs::File;
use std::io::BufReader;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use rustls_pemfile::{certs, pkcs8_private_keys};
use axum_server::tls_rustls::{bind_rustls, RustlsConfig};
use tokio_rustls::rustls::pki_types::PrivateKeyDer;
use tokio_rustls::rustls::ServerConfig;
© www.soinside.com 2019 - 2024. All rights reserved.