HIGH cross site request forgeryactixjwt tokens

Cross Site Request Forgery in Actix with Jwt Tokens

Cross Site Request Forgery in Actix with Jwt Tokens — how this specific combination creates or exposes the vulnerability

Cross Site Request Forgery (CSRF) is an attack that tricks a logged-in victim into submitting unintended requests on a web application. In Actix-web applications that use JWT tokens for authentication, CSRF risks can emerge when token handling and session semantics are not aligned with anti-CSRF defenses. JWTs are often stored in browser-accessible locations (e.g., localStorage) and sent via the Authorization header, which prevents traditional cookie-based CSRF attacks that rely on automatic inclusion of credentials. However, if the application also uses cookie-based session identifiers for other flows, or if JWTs are accepted via cookies or query parameters, the browser may automatically include those tokens in cross-origin requests, creating a CSRF surface.

Specifically in Actix, if endpoints accept JWTs from cookies (rather than strictly from the Authorization header) and do not enforce SameSite cookie attributes or anti-CSRF tokens, an attacker can craft a malicious form or script on another origin that triggers state-changing requests. Browsers will include cookies (and any attached JWTs) automatically, leading to unauthorized actions on behalf of the victim. Even when JWTs are transmitted via headers, developers might inadvertently allow origins to read responses (CORS misconfigurations), enabling attacker-controlled JavaScript to make authenticated requests and exfiltrate results, effectively combining CSRF with token theft patterns. The presence of JWTs does not eliminate CSRF; it shifts the focus to ensuring tokens are never automatically sent by the browser and that requests are validated with additional context such as origin checks or anti-CSRF mechanisms.

Actix-web’s middleware and guard system can inadvertently expose endpoints if CORS is permissive or if session cookies are used alongside JWTs. For example, an endpoint that reads a JWT from a cookie and also permits arbitrary origins without proper CORS configuration may allow an attacker’s site to make authenticated requests via an img or fetch call. Even without cookies, if the application provides any endpoint that changes state via GET or relies on predictable URLs, and does not validate the Origin header or use anti-CSRF tokens, it remains vulnerable. The key takeaway is that JWTs change the transport and storage characteristics but do not remove the need for CSRF mitigation when the application maintains any form of automatic credential conveyance or lacks origin/referrer validation and strict header-based authentication.

Jwt Tokens-Specific Remediation in Actix — concrete code fixes

Remediation focuses on ensuring JWTs are never automatically included by browsers and that requests are verified to originate from a trusted source. The following practices and code examples are specific to Actix-web in Rust.

  • Require the Authorization header for JWTs and avoid cookie-based JWT transmission:
use actix_web::{web, HttpRequest, HttpResponse, Error};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};

async fn validate_jwt_from_header(req: &HttpRequest) -> Result {
    let auth = req.headers().get("Authorization")
        .ok_or_else(|| HttpResponse::Unauthorized().body("Missing Authorization header"))?;
    let token = auth.to_str().map_err(|_| HttpResponse::BadRequest().body("Invalid header"))?
        .strip_prefix("Bearer ")
        .ok_or_else(|| HttpResponse::Unauthorized().body("Invalid token format"))?;
    let _claims = decode::(
        token,
        &DecodingKey::from_secret("your_secret".as_ref()),
        &Validation::new(Algorithm::HS256),
    ).map_err(|_| HttpResponse::Unauthorized().body("Invalid token"))?;
    Ok(token.to_string())
}
  • Set SameSite and Secure cookie attributes if cookies are used at all, and prefer HttpOnly for session cookies:
use actix_web::cookie::{Cookie, SameSite};
use actix_web::HttpResponse;

let mut resp = HttpResponse::Ok().finish();
let cookie = Cookie::build(("session", "value"))
    .same_site(SameSite::Strict)
    .secure(true)
    .http_only(true)
    .path("/")
    .finish();
resp.add_cookie(&cookie);
  • Enforce strict CORS and validate Origin for state-changing methods:
use actix_cors::Cors;
use actix_web::App;

let cors = Cors::default()
    .allowed_origin("https://trusted.example.com")
    .allowed_methods(vec!["GET", "POST"])
    .allowed_header(actix_web::http::header::AUTHORIZATION)
    .supports_credentials()
    .max_age(3600);

App::new()
    .wrap(cors)
    .service(your_routes)
  • Implement anti-CSRF tokens for endpoints that accept cookies or are accessible from browser contexts, even when JWTs are used in headers. Pair a server-side token stored in a SameSite cookie with a custom header requirement:
use actix_web::{web, HttpRequest, HttpResponse};
use uuid::Uuid;

async fn csrf_protected(req: HttpRequest, form: web::Form) -> HttpResponse {
    let session_csrf = req.cookies().find(|c| c.name() == "csrf")
        .map(|c| c.value().to_string())
        .unwrap_or_default();
    let header_csrf = req.headers().get("X-CSRF-Token")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    if session_csrf.is_empty() || session_csrf != header_csrf {
        return HttpResponse::Forbidden().body("Invalid CSRF token");
    }
    // proceed with state-changing logic
    HttpResponse::Ok().finish()
}

These measures ensure that JWTs remain header-only where possible, cookies are hardened, and each request is verified for legitimate origin or token, reducing the likelihood of successful CSRF against Actix services that involve JWT authentication.

Frequently Asked Questions

Does using JWTs in the Authorization header eliminate CSRF risk in Actix?
Not entirely. While Authorization header-based JWTs prevent automatic inclusion by browsers, CSRF risk persists if your application also uses cookies, has permissive CORS, or exposes state-changing GET endpoints. Defense in depth with strict header validation, SameSite/Secure cookies, and anti-CSRF tokens is recommended.
Can middleBrick detect CSRF issues in Actix APIs that use JWTs?
middleBrick scans unauthenticated attack surfaces and checks authentication mechanisms, CORS configuration, and endpoint exposure. It reports findings aligned with OWASP API Top 10, including CSRF-related risks, and provides remediation guidance for Actix and other frameworks.