@@ -8,6 +8,12 @@ use crate::encoding::percent_decode;
88const CSRF_COOKIE_NAME : & str = "csrf_token" ;
99const CSRF_TOKEN_LEN : usize = 16 ; // 128-bit hex token
1010
11+ #[ derive( Clone ) ]
12+ pub struct CsrfConfig {
13+ pub use_secure_cookies : bool ,
14+ pub max_body_size : usize ,
15+ }
16+
1117fn generate_csrf_token ( ) -> String {
1218 let mut buf = [ 0u8 ; CSRF_TOKEN_LEN ] ;
1319 rand:: fill ( & mut buf) ;
@@ -29,7 +35,7 @@ fn extract_csrf_field(body: &[u8]) -> Option<String> {
2935}
3036
3137pub async fn csrf_middleware (
32- State ( use_secure_cookies ) : State < bool > ,
38+ State ( config ) : State < CsrfConfig > ,
3339 req : axum:: http:: Request < axum:: body:: Body > ,
3440 next : Next ,
3541) -> axum:: response:: Response {
@@ -42,7 +48,7 @@ pub async fn csrf_middleware(
4248 if is_post && is_web && !is_login {
4349 let cookie_token_for_check = cookie_token. clone ( ) ;
4450 let ( parts, body) = req. into_parts ( ) ;
45- let bytes = match axum:: body:: to_bytes ( body, 10 * 1024 * 1024 ) . await {
51+ let bytes = match axum:: body:: to_bytes ( body, config . max_body_size ) . await {
4652 Ok ( b) => b,
4753 Err ( _) => {
4854 return ( axum:: http:: StatusCode :: BAD_REQUEST , "request too large" ) . into_response ( ) ;
@@ -71,11 +77,14 @@ pub async fn csrf_middleware(
7177 let mut resp = next. run ( req) . await ;
7278 if needs_cookie {
7379 let token = generate_csrf_token ( ) ;
74- let secure_flag = if use_secure_cookies { "; Secure" } else { "" } ;
75- if let Ok ( val) = format ! (
76- "{CSRF_COOKIE_NAME}={token}; Path=/web; HttpOnly; SameSite=Strict{secure_flag}"
77- )
78- . parse ( )
80+ let secure_flag = if config. use_secure_cookies {
81+ "; Secure"
82+ } else {
83+ ""
84+ } ;
85+ if let Ok ( val) =
86+ format ! ( "{CSRF_COOKIE_NAME}={token}; Path=/web; SameSite=Strict{secure_flag}" )
87+ . parse ( )
7988 {
8089 resp. headers_mut ( ) . append ( "set-cookie" , val) ;
8190 }
0 commit comments