安全最佳实践 #

安全头部 #

添加安全头部中间件 #

rust
use actix_web::middleware::DefaultHeaders;
use actix_web::http::header;

App::new()
    .wrap(DefaultHeaders::new()
        .add(("X-Content-Type-Options", "nosniff"))
        .add(("X-Frame-Options", "DENY"))
        .add(("X-XSS-Protection", "1; mode=block"))
        .add(("Strict-Transport-Security", "max-age=31536000; includeSubDomains"))
        .add(("Content-Security-Policy", "default-src 'self'"))
    )

输入验证 #

使用 validator #

rust
use validator::Validate;
use serde::Deserialize;

#[derive(Deserialize, Validate)]
struct UserInput {
    #[validate(length(min = 2, max = 100))]
    name: String,
    
    #[validate(email)]
    email: String,
    
    #[validate(length(min = 8))]
    password: String,
}

#[actix_web::post("/users")]
async fn create_user(body: web::Json<UserInput>) -> impl Responder {
    if let Err(e) = body.validate() {
        return HttpResponse::BadRequest().json(serde_json::json!({
            "error": e.to_string()
        }));
    }
    
    HttpResponse::Created().finish()
}

密码处理 #

使用 bcrypt #

toml
[dependencies]
bcrypt = "0.15"
rust
use bcrypt::{hash, verify, DEFAULT_COST};

fn hash_password(password: &str) -> Result<String, bcrypt::BcryptError> {
    hash(password, DEFAULT_COST)
}

fn verify_password(password: &str, hash: &str) -> Result<bool, bcrypt::BcryptError> {
    verify(password, hash)
}

HTTPS 配置 #

使用 Rustls #

toml
[dependencies]
actix-web = { version = "4", features = ["rustls"] }
rustls = "0.21"
rustls-pemfile = "1"
rust
use actix_web::{web, App, HttpServer};
use rustls::{Certificate, PrivateKey, ServerConfig};
use std::fs::File;
use std::io::BufReader;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let cert_file = &mut BufReader::new(File::open("cert.pem").unwrap());
    let key_file = &mut BufReader::new(File::open("key.pem").unwrap());
    
    let cert_chain = rustls_pemfile::certs(cert_file)
        .unwrap()
        .into_iter()
        .map(Certificate)
        .collect();
    
    let mut keys = rustls_pemfile::pkcs8_private_keys(key_file)
        .unwrap()
        .into_iter()
        .map(PrivateKey)
        .collect::<Vec<_>>();
    
    let config = ServerConfig::builder()
        .with_safe_defaults()
        .with_no_client_auth()
        .with_single_cert(cert_chain, keys.remove(0))
        .unwrap();
    
    HttpServer::new(|| App::new())
        .bind_rustls("0.0.0.0:443", config)?
        .run()
        .await
}

速率限制 #

简单实现 #

rust
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

struct RateLimiter {
    requests: AtomicU64,
    limit: u64,
}

impl RateLimiter {
    fn new(limit: u64) -> Self {
        Self {
            requests: AtomicU64::new(0),
            limit,
        }
    }
    
    fn check(&self) -> bool {
        self.requests.fetch_add(1, Ordering::SeqCst) < self.limit
    }
}

下一步 #

继续学习 WebSocket 入门,了解实时通信!

最后更新:2026-03-29