Cors

Struct Cors 

Source
pub struct Cors { /* private fields */ }
Expand description

Builder for CORS middleware.

To construct a CORS middleware, call Cors::default() to create a blank, restrictive builder. Then use any of the builder methods to customize CORS behavior.

The alternative Cors::permissive() constructor is available for local development, allowing all origins and headers, etc. The permissive constructor should not be used in production.

§Errors

Errors surface in the middleware initialization phase. This means that, if you have logs enabled in Actix Web (using env_logger or other crate that exposes logs from the log crate), error messages will outline what is wrong with the CORS configuration in the server logs and the server will fail to start up or serve requests.

§Example

use actix_cors::Cors;
use actix_web::http::header;

let cors = Cors::default()
    .allowed_origin("https://www.rust-lang.org")
    .allowed_methods(vec!["GET", "POST"])
    .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
    .allowed_header(header::CONTENT_TYPE)
    .max_age(3600);

// `cors` can now be used in `App::wrap`.

Implementations§

Source§

impl Cors

Source

pub fn permissive() -> Cors

A very permissive set of default for quick development. Not recommended for production use.

All origins, methods, request headers and exposed headers allowed. Credentials supported. Max age 1 hour. Does not send wildcard.

Source

pub fn allow_any_origin(self) -> Cors

Resets allowed origin list to a state where any origin is accepted.

See Cors::allowed_origin for more info on allowed origins.

Source

pub fn allowed_origin(self, origin: &str) -> Cors

Add an origin that is allowed to make requests.

By default, requests from all origins are accepted by CORS logic. This method allows to specify a finite set of origins to verify the value of the Origin request header.

These are origin-or-null types in the Fetch Standard.

When this list is set, the client’s Origin request header will be checked in a case-sensitive manner.

When all origins are allowed and send_wildcard is set, * will be sent in the Access-Control-Allow-Origin response header. If send_wildcard is not set, the client’s Origin request header will be echoed back in the Access-Control-Allow-Origin response header.

If the origin of the request doesn’t match any allowed origins and at least one allowed_origin_fn function is set, these functions will be used to determinate allowed origins.

§Initialization Errors
  • If supplied origin is not valid uri
  • If supplied origin is a wildcard (*). Cors::send_wildcard should be used instead.
Source

pub fn allowed_origin_fn<F>(self, f: F) -> Cors
where F: Fn(&HeaderValue, &RequestHead) -> bool + 'static,

Determinate allowed origins by processing requests which didn’t match any origins specified in the allowed_origin.

The function will receive a RequestHead of each request, which can be used to determine whether it should be allowed or not.

If the function returns true, the client’s Origin request header will be echoed back into the Access-Control-Allow-Origin response header.

Source

pub fn allow_any_method(self) -> Cors

Resets allowed methods list to all methods.

See Cors::allowed_methods for more info on allowed methods.

Source

pub fn allowed_methods<U, M>(self, methods: U) -> Cors
where U: IntoIterator<Item = M>, M: TryInto<Method>, <M as TryInto<Method>>::Error: Into<Error>,

Set a list of methods which allowed origins can perform.

These will be sent in the Access-Control-Allow-Methods response header as specified in the Fetch Standard CORS protocol.

Defaults to [GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]

Source

pub fn allow_any_header(self) -> Cors

Resets allowed request header list to a state where any header is accepted.

See Cors::allowed_headers for more info on allowed request headers.

Source

pub fn allowed_header<H>(self, header: H) -> Cors

Add an allowed request header.

See Cors::allowed_headers for more info on allowed request headers.

Source

pub fn allowed_headers<U, H>(self, headers: U) -> Cors
where U: IntoIterator<Item = H>, H: TryInto<HeaderName>, <H as TryInto<HeaderName>>::Error: Into<Error>,

Set a list of request header field names which can be used when this resource is accessed by allowed origins.

If All is set, whatever is requested by the client in Access-Control-Request-Headers will be echoed back in the Access-Control-Allow-Headers header as specified in the Fetch Standard CORS protocol.

Defaults to All.

Source

pub fn expose_any_header(self) -> Cors

Resets exposed response header list to a state where any header is accepted.

See Cors::expose_headers for more info on exposed response headers.

Source

pub fn expose_headers<U, H>(self, headers: U) -> Cors
where U: IntoIterator<Item = H>, H: TryInto<HeaderName>, <H as TryInto<HeaderName>>::Error: Into<Error>,

Set a list of headers which are safe to expose to the API of a CORS API specification. This corresponds to the Access-Control-Expose-Headers response header as specified in the Fetch Standard CORS protocol.

This defaults to an empty set.

Source

pub fn max_age(self, max_age: impl Into<Option<usize>>) -> Cors

Set a maximum time (in seconds) for which this CORS request maybe cached. This value is set as the Access-Control-Max-Age header as specified in the Fetch Standard CORS protocol.

Pass a number (of seconds) or use None to disable sending max age header.

Source

pub fn send_wildcard(self) -> Cors

Set to use wildcard origins.

If send wildcard is set and the allowed_origins parameter is All, a wildcard Access-Control-Allow-Origin response header is sent, rather than the request’s Origin header.

This CANNOT be used in conjunction with allowed_origins set to All and allow_credentials set to true. Depending on the mode of usage, this will either result in an CorsError::CredentialsWithWildcardOrigin error during actix launch or runtime.

Defaults to false.

Source

pub fn supports_credentials(self) -> Cors

Allows users to make authenticated requests

If true, injects the Access-Control-Allow-Credentials header in responses. This allows cookies and credentials to be submitted across domains as specified in the Fetch Standard CORS protocol.

This option cannot be used in conjunction with an allowed_origin set to All and send_wildcards set to true.

Defaults to false.

A server initialization error will occur if credentials are allowed, but the Origin is set to send wildcards (*); this is not allowed by the CORS protocol.

Source

pub fn disable_vary_header(self) -> Cors

Disable Vary header support.

When enabled the header Vary: Origin will be returned as per the Fetch Standard implementation guidelines.

Setting this header when the Access-Control-Allow-Origin is dynamically generated (eg. when there is more than one allowed origin, and an Origin other than ‘*’ is returned) informs CDNs and other caches that the CORS headers are dynamic, and cannot be cached.

By default, Vary header support is enabled.

Source

pub fn disable_preflight(self) -> Cors

Disable support for preflight requests.

When enabled CORS middleware automatically handles OPTIONS requests. This is useful for application level middleware.

By default preflight support is enabled.

Trait Implementations§

Source§

impl Debug for Cors

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Cors

Source§

fn default() -> Cors

A restrictive (security paranoid) set of defaults.

No allowed origins, methods, request headers or exposed headers. Credentials not supported. No max age (will use browser’s default).

Source§

impl<S, B> Transform<S> for Cors
where S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>, <S as Service>::Future: 'static, B: 'static,

Source§

type Request = ServiceRequest

Requests handled by the service.
Source§

type Response = ServiceResponse<B>

Responses given by the service.
Source§

type Error = Error

Errors produced by the service.
Source§

type InitError = ()

Errors produced while building a transform service.
Source§

type Transform = CorsMiddleware<S>

The TransformService value created by this factory
Source§

type Future = Ready<Result<<Cors as Transform<S>>::Transform, <Cors as Transform<S>>::InitError>>

The future response value.
Source§

fn new_transform(&self, service: S) -> <Cors as Transform<S>>::Future

Creates and returns a new Transform component, asynchronously
Source§

fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, F, E>
where Self: Sized, F: Fn(Self::InitError) -> E + Clone,

Map this transforms’s factory error to a different error, returning a new transform service factory.

Auto Trait Implementations§

§

impl Freeze for Cors

§

impl !RefUnwindSafe for Cors

§

impl !Send for Cors

§

impl !Sync for Cors

§

impl Unpin for Cors

§

impl !UnwindSafe for Cors

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,