Class Cors

java.lang.Object
com.jsgalactic.axiom.security.Cors
All Implemented Interfaces:
Middleware

public final class Cors extends Object implements Middleware
Cross-origin resource sharing (the Fetch standard's CORS protocol) as global middleware, with a strict allow-list of origins.

 app.use(Cors.builder()
         .allowOrigin("https://app.example.com")
         .allowMethods("GET", "POST", "DELETE")
         .allowHeaders("Content-Type", "Authorization")
         .exposeHeaders("X-Request-ID")
         .allowCredentials()
         .maxAge(Duration.ofMinutes(10))
         .build());
 

Configuration is checked when Cors.Builder.build() runs, so an unsafe setup never serves a request: at least one origin is required; origins are exact scheme://host[:port] values (no paths, wildcards, user information or null); the wildcard origin (Cors.Builder.anyOrigin()) cannot be combined with credentials, because a browser refuses the combination and an echoed origin would amount to allowing every site; methods and headers are explicit tokens, never *.

Requests with an Origin header whose origin is on the allow-list receive Access-Control-Allow-Origin with that exact origin (or * for anyOrigin()), Access-Control-Allow-Credentials: true if enabled, and Access-Control-Expose-Headers if configured. A request from any other origin is not blocked, since CORS is enforced by the browser and is no authentication: it is answered normally without any CORS header, which makes the browser refuse to expose the response. The comparison is exact and case-sensitive on the serialized origin, so https://app.example.com.evil.test, a different port or scheme, and a list of several origins never match.

Preflight is an OPTIONS request with Origin and Access-Control-Request-Method. The middleware runs the rest of the chain first, which for a routed path is the router's automatic OPTIONS answer (204 with Allow), and only decorates a successful answer. It adds Access-Control-Allow-Origin, Access-Control-Allow-Methods (the configured methods the route also allows), Access-Control-Allow-Headers (the requested headers) and Access-Control-Max-Age when the origin is allowed, the requested method is configured and, when the answer has an Allow header, supported by the route, and every requested header is configured. Otherwise the answer is left without CORS headers, so the browser fails the preflight. Unrouted paths keep their 404, so a preflight never succeeds for a path that does not exist. An application's own OPTIONS route is passed through and decorated the same way.

Vary: Origin is added to every response unless anyOrigin() is used, and a preflight also varies on the two request headers, so caches never serve a response meant for one origin to another. Existing Vary values are kept.

Placement. Register it globally with app.use(...); group middleware do not run for the router's own answers, so a group-scoped instance would not see preflights. The middleware is immutable and thread-safe. It also decorates responses mapped from exceptions (a 401 from a policy, for example) through Middleware.afterError(com.jsgalactic.axiom.context.Context, com.jsgalactic.axiom.http.Response), so a browser sees the status instead of a CORS failure; a preflight whose chain failed gets only Vary.

  • Method Details

    • builder

      public static Cors.Builder builder()
      Starts a configuration.
      Returns:
      a new builder
    • handle

      public Response handle(Context context, Middleware.Next next) throws Exception
      Description copied from interface: Middleware
      Handles one request, usually by calling next.run().
      Specified by:
      handle in interface Middleware
      Parameters:
      context - the request-scoped context shared with the handler; status settings made here apply to the handler's result mapping
      next - the rest of the chain
      Returns:
      the response to use; never null
      Throws:
      Exception - to fail the request as a handler exception would
    • afterError

      public Response afterError(Context context, Response response)
      Description copied from interface: Middleware
      Decorates a response that was produced from an exception: a problem response for an AxiomException, the response of an error handler, the generic 500, or the 406 for an unacceptable response type. The default returns the response unchanged.

      It is called once per such response for each middleware that was entered when the failure happened (a middleware an outer one short-circuited before was never entered), innermost first, after error mapping and before the response leaves app.handle. It is not called for responses that come back through Middleware.Next.run(), including responses a middleware or handler builds itself, nor for the router's 404, 405 and 501 answers (those flow through global middleware as ordinary responses), nor for failures before routing (413, CONNECT) and listener errors. An exception that nothing maps, and a request that was cancelled or timed out, never reach it.

      Like Middleware.handle(com.jsgalactic.axiom.context.Context, com.jsgalactic.axiom.context.Middleware.Next), it runs on the request's thread under the request deadline and must be thread-safe. It must not throw: an exception from it is not mapped again. An AxiomException answers with its own undecorated problem response and anything else fails the request as an unexpected exception.

      Specified by:
      afterError in interface Middleware
      Parameters:
      context - the failed request's context
      response - the response produced from the exception, never null
      Returns:
      the response to pass outwards; never null