pub struct CsrfMiddleware { /* private fields */ }
Expand description
Actix Web middleware providing CSRF protection.
Supports two patterns:
- Double-Submit Cookie (default): a token is stored in a cookie and echoed by the client.
- Synchronizer Token (with
actix-session
): a token is stored server-side in the session.
§How It Works
- For safe methods (GET/HEAD), the middleware ensures a token exists and may set it in cookies. For the Double-Submit Cookie pattern, an anonymous pre-session cookie may be issued before the user is authenticated.
- For mutating methods (POST/PUT/PATCH/DELETE), a token is required. The middleware
accepts tokens from the header
DEFAULT_CSRF_TOKEN_HEADER
or the body fieldDEFAULT_CSRF_TOKEN_FIELD
for JSON or url-encoded bodies.multipart/form-data
is rejected unlessCsrfMiddlewareConfig::with_multipart
is enabled. - On successful validation, the token is rotated.
- Optional strict Origin/Referer checks can be enabled via
CsrfMiddlewareConfig::with_enforce_origin
.
§Examples
Double-Submit Cookie (no session middleware required):
use actix_csrf_middleware::{CsrfMiddleware, CsrfMiddlewareConfig, CsrfToken};
use actix_web::{web, App, HttpResponse};
let secret = b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // >= 32 bytes
let cfg = CsrfMiddlewareConfig::double_submit_cookie(secret);
let app = App::new()
.wrap(CsrfMiddleware::new(cfg))
.service(
web::resource("/form").route(web::get().to(|csrf: CsrfToken| async move {
Ok::<_, actix_web::Error>(HttpResponse::Ok().body(format!("token:{}", csrf.0)))
}))
)
.service(
web::resource("/submit").route(web::post().to(|_csrf: CsrfToken| async move {
Ok::<_, actix_web::Error>(HttpResponse::Ok())
}))
);
Synchronizer Token (requires actix-session
) example:
ⓘ
use actix_csrf_middleware::{CsrfMiddleware, CsrfMiddlewareConfig};
use actix_session::{storage::CookieSessionStore, SessionMiddleware};
use actix_web::{App, cookie::Key};
let cfg = CsrfMiddlewareConfig::synchronizer_token(b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
let app = App::new()
.wrap(SessionMiddleware::new(CookieSessionStore::default(), Key::generate()))
.wrap(CsrfMiddleware::new(cfg));
Implementations§
Source§impl CsrfMiddleware
impl CsrfMiddleware
Sourcepub fn new(config: CsrfMiddlewareConfig) -> Self
pub fn new(config: CsrfMiddlewareConfig) -> Self
Creates a CSRF middleware instance with the given configuration.
See CsrfMiddlewareConfig
for available options and examples.
Trait Implementations§
Source§impl<S, B> Transform<S, ServiceRequest> for CsrfMiddleware
impl<S, B> Transform<S, ServiceRequest> for CsrfMiddleware
Source§type Response = ServiceResponse<EitherBody<B>>
type Response = ServiceResponse<EitherBody<B>>
Responses produced by the service.
Source§type Transform = CsrfMiddlewareService<S>
type Transform = CsrfMiddlewareService<S>
The
TransformService
value created by this factorySource§type Future = Ready<Result<<CsrfMiddleware as Transform<S, ServiceRequest>>::Transform, <CsrfMiddleware as Transform<S, ServiceRequest>>::InitError>>
type Future = Ready<Result<<CsrfMiddleware as Transform<S, ServiceRequest>>::Transform, <CsrfMiddleware as Transform<S, ServiceRequest>>::InitError>>
The future response value.
Source§fn new_transform(&self, service: S) -> Self::Future
fn new_transform(&self, service: S) -> Self::Future
Creates and returns a new Transform component, asynchronously
Auto Trait Implementations§
impl Freeze for CsrfMiddleware
impl RefUnwindSafe for CsrfMiddleware
impl !Send for CsrfMiddleware
impl !Sync for CsrfMiddleware
impl Unpin for CsrfMiddleware
impl UnwindSafe for CsrfMiddleware
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more