| name | bx-csrf |
| description | Use this skill for CSRF (Cross-Site Request Forgery) protection in BoxLang web apps: CSRFGenerateToken(), CSRFVerifyToken(), CSRFHiddenField(), CSRFRotate(), token scoping with keys, auto-verification, token expiration, and boxlang.json configuration. |
bx-csrf: CSRF Protection
Installation
install-bx-module bx-csrf
box install bx-csrf
BIFs
| BIF | Description |
|---|
CSRFGenerateToken( [key], [forceNew] ) | Generate a CSRF token (optionally scoped to a key) |
CSRFVerifyToken( token, [key] ) | Verify a CSRF token (returns boolean) |
CSRFHiddenField( [key], [forceNew] ) | Generate a ready-to-embed <input type="hidden"> HTML field |
CSRFRotate() | Rotate/invalidate all current tokens, forcing regeneration |
Basic Form Protection
<form method="POST" action="/submit">
<bx:output>#CSRFHiddenField()#</bx:output>
<input type="text" name="email" />
<button type="submit">Submit</button>
</form>
function processForm() {
if ( !CSRFVerifyToken( form.csrf ) ) {
throw( type: "Security.CSRFTokenInvalid", message: "Invalid CSRF token" )
}
}
Scoped Tokens (Per-Form)
Use scoped tokens when you have multiple forms on the same page or need per-action tokens:
token = CSRFGenerateToken( "deleteUser" )
if ( !CSRFVerifyToken( form.csrf, "deleteUser" ) ) {
throw( type: "Security.CSRFTokenInvalid", message: "Invalid delete token" )
}
<bx:output>#CSRFHiddenField( "deleteUser" )#</bx:output>
AJAX / API Requests (Header-Based)
if ( !CSRFVerifyToken( getHTTPRequestData().headers[ "X-CSRF-Token" ] ?: "" ) ) {
throw( type: "Security.CSRFTokenInvalid", message: "Missing or invalid CSRF token" )
}
Token Rotation
CSRFRotate()
Configuration (boxlang.json)
{
"modules": {
"csrf": {
"settings": {
"cacheStorage" : "session",
"rotationInterval" : 30,
"timeoutSkew" : 120,
"reapFrequency" : 1,
"autoVerify" : false,
"headerName" : "x-csrf-token",
"verifyMethods" : ["POST", "PUT", "PATCH", "DELETE"]
}
}
}
}
Auto-Verification
When autoVerify: true, every POST/PUT/PATCH/DELETE request is automatically checked for a valid CSRF token in the x-csrf-token header. No manual verification code needed.
Common Pitfalls
- ✅ Always include the CSRF token for any state-changing request (POST, PUT, DELETE, PATCH)
- ❌ GET requests should NEVER change state — CSRF protection only applies to non-GET methods
- ✅ Use scoped tokens (
key param) to differentiate between multiple forms on the same page
- ❌ Don't skip
CSRFRotate() after login/logout — stale tokens from old sessions are a risk
- ✅ For SPA/AJAX apps, retrieve the token server-side and embed it in the page on initial render