actix_security_core/http/security/websocket/mod.rs
1//! WebSocket Security module for Actix Web.
2//!
3//! # Overview
4//!
5//! This module provides security features for WebSocket connections:
6//! - Authentication during the WebSocket handshake
7//! - Origin validation (CSWSH prevention)
8//! - Security context propagation to WebSocket actors
9//!
10//! # How It Works
11//!
12//! WebSocket security works by securing the HTTP upgrade request:
13//!
14//! ```text
15//! Client Server
16//! | |
17//! |--HTTP Upgrade Request--->|
18//! | (with auth token) | 1. SecurityTransform validates auth
19//! | | 2. Origin validation (CSWSH check)
20//! | | 3. Store user in extensions
21//! |<--101 Switching----------|
22//! | |
23//! |==WebSocket Connection====| User available via SecurityContext
24//! | |
25//! ```
26//!
27//! # Usage
28//!
29//! ## Basic WebSocket Authentication
30//!
31//! ```ignore
32//! use actix_web::{get, web, HttpRequest, HttpResponse};
33//! use actix_security::http::security::{SecurityExt, websocket::OriginValidator};
34//!
35//! #[get("/ws")]
36//! async fn ws_handler(
37//! req: HttpRequest,
38//! stream: web::Payload,
39//! ) -> Result<HttpResponse, actix_web::Error> {
40//! // 1. Check authentication (user already set by SecurityTransform)
41//! let user = req.get_user().ok_or(AuthError::Unauthorized)?;
42//!
43//! // 2. Validate origin (CSWSH prevention)
44//! OriginValidator::new(&["https://myapp.com"])
45//! .validate(&req)?;
46//!
47//! // 3. Upgrade to WebSocket
48//! let resp = actix_ws::start(MyWebSocketActor::new(user), &req, stream)?;
49//! Ok(resp)
50//! }
51//! ```
52//!
53//! ## Using WebSocket Security Config
54//!
55//! ```ignore
56//! use actix_security::http::security::websocket::WebSocketSecurityConfig;
57//!
58//! let ws_config = WebSocketSecurityConfig::new()
59//! .allowed_origins(vec!["https://myapp.com".into()])
60//! .require_authentication(true);
61//!
62//! #[get("/ws")]
63//! async fn ws_handler(
64//! req: HttpRequest,
65//! stream: web::Payload,
66//! config: web::Data<WebSocketSecurityConfig>,
67//! ) -> Result<HttpResponse, actix_web::Error> {
68//! // Validate the upgrade request
69//! let user = config.validate_upgrade(&req)?;
70//!
71//! // Upgrade to WebSocket
72//! let resp = actix_ws::start(MyWebSocketActor::new(user), &req, stream)?;
73//! Ok(resp)
74//! }
75//! ```
76//!
77//! ## Security Context in WebSocket Actor
78//!
79//! ```ignore
80//! use actix_security::http::security::{User, SecurityContext};
81//!
82//! struct MyWebSocketActor {
83//! user: User,
84//! }
85//!
86//! impl MyWebSocketActor {
87//! pub fn new(user: User) -> Self {
88//! Self { user }
89//! }
90//!
91//! fn handle_message(&self, msg: &str) {
92//! // Access user directly
93//! if self.user.has_role("ADMIN") {
94//! // Admin-only logic
95//! }
96//! }
97//! }
98//! ```
99//!
100//! # Spring Security Comparison
101//!
102//! | Spring Security | Actix Security |
103//! |-----------------|----------------|
104//! | `WebSocketSecurityConfigurer` | `WebSocketSecurityConfig` |
105//! | `AbstractSecurityWebSocketMessageBrokerConfigurer` | Security middleware + OriginValidator |
106//! | `@PreAuthorize` on message handlers | Manual checks in actor |
107//! | CORS/Origin checking | `OriginValidator` |
108//!
109//! # Security Best Practices
110//!
111//! 1. **Always use TLS** - Use `wss://` in production
112//! 2. **Validate Origin** - Prevent Cross-Site WebSocket Hijacking (CSWSH)
113//! 3. **Authenticate during handshake** - Before WebSocket upgrade
114//! 4. **Set message size limits** - Prevent DoS attacks
115//! 5. **Implement timeouts** - Close idle connections
116
117mod config;
118mod error;
119mod extractor;
120mod origin;
121
122pub use config::{WebSocketSecurityConfig, WebSocketSecurityConfigBuilder};
123pub use error::WebSocketSecurityError;
124pub use extractor::{WebSocketUpgrade, WebSocketUser};
125pub use origin::{OriginValidator, OriginValidatorBuilder};