CORS and CSRF Protection
Mu Server comes with handlers for both CORS and CSRF protection.
CORS
CORS (Cross-Origin Resource Sharing) lets your server control which origins, headers, and methods are permitted for cross-origin requests. By default, modern browsers will block cross-origin requests, however you can opt in to allow other origins to call your server by specifying CORS config as a handler or on a RestHandlerBuilder.
Full example:
public class CORSExample {
public static void main(String[] args) {
CORSConfig corsConfig = CORSConfigBuilder.corsConfig()
// the origins allowed (no need to specify your own origin)
.withAllowedOrigins("https://example.com")
// also allow requests from localhost (useful for development)
.withLocalhostAllowed()
// the headers that cross origins can send
.withAllowedHeaders("Content-Type", "Authorization")
// the headers that are allowed to be read by the browser
.withExposedHeaders("X-Custom-Header")
// allow cookies and credentials to be sent by the browser
.withAllowCredentials(true)
// Cache preflight response for 1 hour
.withMaxAge(3600)
.build();
// Preferred way to configure CORS when using jax-rs
MuServer server = MuServerBuilder.httpServer()
.addHandler(RestHandlerBuilder.restHandler(/* resources */)
.withCORS(corsConfig)
)
.start();
// Or, if you are not using jax-rs, you can add a CORS handler in which case the methods
// need to be added manually
server = MuServerBuilder.httpServer()
.addHandler(CORSHandlerBuilder.corsHandler()
.withAllowedMethods(Method.GET, Method.HEAD, Method.POST)
.withCORSConfig(corsConfig)
)
.addHandler(Method.GET, "/", (request, response, pathParams) -> {
response.write("Hello, world");
})
.start();
System.out.println("Started server at " + server.uri());
}
}
(see full file)
See CORSConfigBuilder for full documentation.
CSRF
CSRF (Cross-Site Request Forgery) protection in Mu Server works by rejecting cross-origin, non-safe browser requests using Fetch metadata and Origin headers. The handler automatically applies the following logic:
- Allows all GET, HEAD, or OPTIONS requests (safe methods).
- If the
Origin
header matches a configured allow-list, the request is allowed. - If
Sec-Fetch-Site
is present:- Allows if value is
same-origin
ornone
. - Rejects otherwise.
- Allows if value is
- If neither
Sec-Fetch-Site
norOrigin
are present, the request is allowed (non-modern browsers). - If
Origin
host matchesHost
header, the request is allowed; otherwise, it is rejected.
This approach, explained here, secures modern browsers and can be customized for edge cases.
To use CSRF protection, add the handler as shown below:
public class CSRFProtectionExample {
public static void main(String[] args) {
MuServer server = MuServerBuilder.httpServer()
.addHandler(CSRFProtectionHandlerBuilder.csrfProtection())
.addHandler(Method.POST, "/submit", (request, response, pp) -> {
response.write("Form submitted successfully!");
})
.start();
System.out.println("Started server at " + server.uri());
}
}
(see full file)
Extra options for CSRF protection:
- Allowed Origins: Configure trusted origins that bypass CSRF checks.
- Bypass Paths: Exclude specific routes from CSRF protection (e.g., for SSO or health checks).
- Custom Rejection Handlers: Define custom responses when a request is rejected (e.g., error page or JSON).
See CSRFProtectionHandlerBuilder for full documentation.