Skip to main content

CookieSession

Struct CookieSession 

Source
pub struct CookieSession(/* private fields */);
Expand description

Use cookies for session storage.

CookieSession creates sessions which are limited in size (as the payload must fit into a single cookie). An Internal Server Error is generated if the signed or encrypted, percent-encoded name=value pair exceeds 4096 bytes. Cookie attributes are not counted toward this limit.

A cookie may have a security policy of signed or private. Each has a respective CookieSession constructor.

A signed cookie is stored on the client as plaintext alongside a signature such that the cookie may be viewed but not modified by the client.

A private cookie is stored on the client as encrypted text such that it may neither be viewed nor modified by the client.

The constructors take a key as an argument. Keep this key secret and stable; changing it makes existing session cookies unreadable. The constructors require at least 32 bytes.

Missing, malformed, tampered, undecryptable, or invalid-JSON cookies load an empty session and are replaced. A new cookie is sent when no valid session cookie was loaded, when the session changes or is renewed, or (with expires_in) on each response returned by the inner service. Session::purge instead expires the cookie, preserving its configured scope and security attributes. Inner service errors propagate without writing a cookie.

The backend relies on cookie crate to create and read cookies. Cookie values are percent encoded.

Defaults: name ntex-session, path /, Secure and HttpOnly set, no domain, SameSite, Max-Age or Expires. Configuration methods replace their previous values and do not validate cookie attributes.

§Panics

Configuration methods panic while this backend is shared with a live middleware service. Writing a cookie panics if its configured attributes cannot form a valid Set-Cookie header, or if its expiration is outside the range supported by time::OffsetDateTime.

§Example

use ntex_session::CookieSession;
use ntex::web::{self, App, HttpResponse};

let app = App::default().middleware(
    CookieSession::signed(&[0; 32])
        .domain("www.rust-lang.org")
        .name("ntex-session")
        .path("/")
        .secure(true))
    .service(web::resource("/").to(|| async { HttpResponse::Ok() }));

Implementations§

Source§

impl CookieSession

Source

pub fn signed(key: &[u8]) -> Self

Constructs a signed CookieSession.

The client can read but not modify the session state.

§Panics

Panics if key is shorter than 32 bytes.

Source

pub fn private(key: &[u8]) -> Self

Constructs an encrypted CookieSession.

The session state is encrypted, the client can neither read nor modify it.

§Panics

Panics if key is shorter than 32 bytes.

Source

pub fn path<S: Into<String>>(self, value: S) -> Self

Sets the session cookie’s Path attribute.

Default is /.

§Panics

Panics if this backend is shared with a live middleware service, or if value contains ; or characters other than printable ASCII.

Source

pub fn name<S: Into<String>>(self, value: S) -> Self

Sets the session cookie’s name.

Default is ntex-session. Names with the __Secure- prefix require secure; __Host- also requires path / and no domain.

§Panics

Panics if this backend is shared with a live middleware service.

Source

pub fn domain<S: Into<String>>(self, value: S) -> Self

Sets the session cookie’s Domain attribute.

Not set by default, the cookie is sent only to the origin host.

§Panics

Panics if this backend is shared with a live middleware service, or if value contains ; or characters other than printable ASCII.

Source

pub fn secure(self, value: bool) -> Self

Sets the session cookie’s Secure attribute.

If the secure field is set, a cookie will only be transmitted when the connection is secure - i.e. https. Default is true, set it to false to use sessions over plain http.

§Panics

Panics if this backend is shared with a live middleware service.

Source

pub fn http_only(self, value: bool) -> Self

Sets the session cookie’s HttpOnly attribute.

If set, the cookie is not available to client side scripts. Default is true.

§Panics

Panics if this backend is shared with a live middleware service.

Source

pub fn same_site(self, value: SameSite) -> Self

Sets the session cookie’s SameSite attribute.

Not set by default.

§Panics

Panics if this backend is shared with a live middleware service.

Source

pub fn max_age(self, seconds: i64) -> Self

Sets the session cookie’s Max-Age attribute, in seconds.

Unset by default. If expires_in is also unset, the cookie expires when the browser session ends.

§Panics

Panics if this backend is shared with a live middleware service.

Source

pub fn max_age_time(self, value: Duration) -> Self

Sets the session cookie’s Max-Age attribute.

Same as max_age, but takes a time::Duration.

§Panics

Panics if this backend is shared with a live middleware service.

Source

pub fn expires_in(self, seconds: i64) -> Self

Sets the session cookie’s Expires to the given number of seconds from now.

The cookie is re-sent on each response returned by the inner service, unless the session is purged, so its expiration is extended on each request. Unset by default. If Max-Age is also configured, browsers give it precedence over Expires.

§Panics

Panics if this backend is shared with a live middleware service.

Source

pub fn expires_in_time(self, value: Duration) -> Self

Sets the session cookie’s Expires to the given duration from now.

Same as expires_in, but takes a time::Duration.

§Panics

Panics if this backend is shared with a live middleware service.

Trait Implementations§

Source§

impl<S, St> Middleware<S, St> for CookieSession

Source§

type Service = CookieSessionMiddleware<S>

Wrapper returned by Self::create. Read more
Source§

fn create(&self, _: &St, service: S) -> Self::Service

Wraps service using the supplied construction state. Read more
Source§

fn apply_to<Sf, Req>( self, factory: Sf, ) -> ServiceChainFactory<ApplyMiddleware<Self, Sf>, St, Req>
where Sf: ServiceFactory<St, Req, Service = S>, Self: Sized, Self::Service: Service<St, Req>,

Creates a service factory that instantiates a service and applies the current middleware to it. Read more

Auto Trait Implementations§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = !

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

fn try_from(value: U) -> Result<T, !>

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