Cross-Origin Resource Sharing (CORS) is a mechanism that is necessary when you want websites from other sites being able to access your webservice. This requirement most often emerges when a modern web frontend is served on another host (or just port) than the backend. This chapter explains how to configure HttpMaid accordingly.
To add CORS to your HttpMaid instance, the class
offers two configurator methods:
They both return a
CorsConfigurator object for futher configuration
and differ only in the hosts they accept cross-origin requests from.
toActivateCORSWithAllowedOrigins() takes an arbitrary number of allowed
hostnames as parameters while
allows all hosts to perform cross-origin requests (use with caution).
Both configurations set the
accordingly - see here for more information.
CorsConfigurator object provides the following methods for further
withAllowedMethods()- configures the request methods cross-origin requests may use (default is
POST). This sets the
Access-Control-Allow-Methodsheader - see here for more information.
allowingAllHeaders()- configures the non-standard headers cross-origin requests may use (default is none). This sets the
Access-Control-Allow-Headersheader in response to the
Access-Control-Request-Headersheader - see here for more information.
exposingAllResponseHeaders()- configures which non-standard response headers the browser will expose to the caller of a cross-origin request (default is none). This sets the
Access-Control-Expose-Headersheader - see here for more information.
notAllowingCredentials()- configures whether browsers should let the callers of cross-origin requests that contain credentials see the respective response (default is to not let them). This sets the
Access-Control-Allow-Credentialsheader - see here for more information.
withTimeOutAfter()- provides browsers with a timeout after which they need to invalidate the queried CORS information (not set by default which will cause browsers to use their respective default settings). This sets the
Access-Control-Max-Ageheader - see here for more information.
final HttpMaid httpMaid = anHttpMaid() .put("/api", (request, response) -> response.setBody("Version 1.0")) .configured(toActivateCORSWithAllowedOrigins("frontend.example.org").withAllowedMethods(PUT)) .build();