Package io.muserver.handlers
Class CSRFProtectionHandlerBuilder
- java.lang.Object
-
- io.muserver.handlers.CSRFProtectionHandlerBuilder
-
- All Implemented Interfaces:
MuHandlerBuilder<CSRFProtectionHandler>
public class CSRFProtectionHandlerBuilder extends java.lang.Object implements MuHandlerBuilder<CSRFProtectionHandler>
Builder for
CSRFProtectionHandler
which protects against Cross-Site Request Forgery (CSRF) by rejecting non-safe cross-origin browser requests.Allows configuration of trusted origins, bypass patterns, and a custom rejection handler.
-
-
Constructor Summary
Constructors Constructor Description CSRFProtectionHandlerBuilder()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description CSRFProtectionHandlerBuilder
addBypassPath(java.lang.String path)
Adds a bypass path.CSRFProtectionHandlerBuilder
addTrustedOrigin(java.lang.String origin)
Adds a trusted origin.CSRFProtectionHandler
build()
static CSRFProtectionHandlerBuilder
csrfProtection()
Creates a new builder.CSRFProtectionHandlerBuilder
withRejectionHandler(MuHandler handler)
Sets a custom handler to execute when a request is rejected due to CSRF protection.
-
-
-
Method Detail
-
addTrustedOrigin
public CSRFProtectionHandlerBuilder addTrustedOrigin(java.lang.String origin)
Adds a trusted origin. Requests with anOrigin
header exactly matching this value are allowed.- Parameters:
origin
- The trusted origin (e.g.https://example.com
)- Returns:
- This builder
-
addBypassPath
public CSRFProtectionHandlerBuilder addBypassPath(java.lang.String path)
Adds a bypass path. Requests to this path are always allowed.- Parameters:
path
- The path to bypass (e.g./api/health
)- Returns:
- This builder
-
withRejectionHandler
public CSRFProtectionHandlerBuilder withRejectionHandler(MuHandler handler)
Sets a custom handler to execute when a request is rejected due to CSRF protection.The provided handler will be invoked whenever a request fails CSRF validation. The handler can perform custom logic such as logging, returning a specific error response, or allowing the request to proceed by returning
false
from itshandle
method.If no custom handler is set, a default handler will throw a
BadRequestException
.Example usage:
builder.withRejectionHandler((request, response) -> { System.out.println("CSRF protection triggered for request to " + request.uri() + " with headers: " + request.headers()); response.status(400); response.write("Forbidden"); return true; });
- Parameters:
handler
- TheMuHandler
to execute when a request is rejected by CSRF protection, ornull
for a default handler.- Returns:
- This builder instance for method chaining.
-
build
public CSRFProtectionHandler build()
- Specified by:
build
in interfaceMuHandlerBuilder<CSRFProtectionHandler>
- Returns:
- A newly built
MuHandler
-
csrfProtection
public static CSRFProtectionHandlerBuilder csrfProtection()
Creates a new builder.- Returns:
- A new CSRFHandlerBuilder
-
-