Skip to main content

Crate trillium_cors

Crate trillium_cors 

Source
Expand description

§Cross-origin resource sharing for trillium.rs

By default a browser will not let a page read a response from a different origin than the page itself. This handler is how a server says which origins it will make an exception for, implementing the Fetch standard’s CORS protocol.

use trillium_cors::Cors;
use trillium::Method;

let app = (
    Cors::allow_origins(["https://app.example.com"])
        .allow_methods([Method::Get, Method::Post, Method::Delete])
        .allow_headers(["content-type", "authorization"]),
    "hello from an api",
);

Mount it ahead of the rest of the application. It does two things: it answers the OPTIONS preflight a browser sends before any request that isn’t a plain GET, HEAD, or form POST, and it adds the headers that let a page read the response to the requests that follow.

§The browser is the enforcement point

CORS is not a server-side access control. A request from an origin this handler does not allow still runs; what the browser withholds is the page’s ability to read the response. So a disallowed origin is answered normally, minus the CORS headers, and a request with no Origin header at all passes through untouched — which is what keeps non-browser clients working. Cors::reject_disallowed_origins trades that for a 403.

Anything that must actually be denied — authentication, authorization, CSRF — needs a handler that enforces it, whether or not this one is present.

§WebSockets

Browsers do not apply CORS to the WebSocket handshake; RFC 6455 assigns that check to the server, which has to compare the Origin header itself. This handler does not cover it, and adding it to an application will not protect a WebSocket endpoint.

Modules§

log_formatter
Formatters for use with a request logger.

Structs§

Cors
Cross-origin resource sharing.

Enums§

Origin
The origin of an URL

Traits§

CorsConnExt
Extends Conn with access to the CORS decision made for this request.

Functions§

cors
Alias for Cors::allow_origins.