mirror of
https://github.com/actix/actix-extras.git
synced 2024-11-24 16:02:59 +01:00
110 lines
16 KiB
HTML
110 lines
16 KiB
HTML
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="Session management for Actix Web."><title>actix_session - Rust</title><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/SourceSerif4-Regular-46f98efaafac5295.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/FiraSans-Regular-018c141bf0843ffd.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/FiraSans-Medium-8f9a781e4970d388.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/SourceCodePro-Regular-562dcc5011b6de7d.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/SourceSerif4-Bold-a2c9cd1067f8b328.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../static.files/SourceCodePro-Semibold-d899c5a5c4aeb14a.ttf.woff2"><link rel="stylesheet" href="../static.files/normalize-76eba96aa4d2e634.css"><link rel="stylesheet" href="../static.files/rustdoc-ae1b282cda4c21ec.css"><meta name="rustdoc-vars" data-root-path="../" data-static-root-path="../static.files/" data-current-crate="actix_session" data-themes="" data-resource-suffix="" data-rustdoc-version="1.74.0-nightly (ca2b74f1a 2023-09-14)" data-channel="nightly" data-search-js="search-5d3eaacf19ebf04f.js" data-settings-js="settings-74424d7eec62a23e.js" data-theme-light-css="light-f194925aa375ae96.css" data-theme-dark-css="dark-1dd4d1ce031e15de.css" data-theme-ayu-css="ayu-49e58d069f567085.css" ><script src="../static.files/storage-db41da1a38ea3cb8.js"></script><script defer src="../crates.js"></script><script defer src="../static.files/main-cabe4b1bd7b9da95.js"></script><noscript><link rel="stylesheet" media="(prefers-color-scheme:light)" href="../static.files/light-f194925aa375ae96.css"><link rel="stylesheet" media="(prefers-color-scheme:dark)" href="../static.files/dark-1dd4d1ce031e15de.css"><link rel="stylesheet" href="../static.files/noscript-cffde32267a19fd6.css"></noscript><link rel="icon" href="https://actix.rs/favicon.ico"></head><body class="rustdoc mod crate"><!--[if lte IE 11]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="mobile-topbar"><button class="sidebar-menu-toggle">☰</button><a class="logo-container" href="../actix_session/index.html"><img src="https://actix.rs/img/logo.png" alt="logo"></a><h2></h2></nav><nav class="sidebar"><a class="logo-container" href="../actix_session/index.html"><img src="https://actix.rs/img/logo.png" alt="logo"></a><h2 class="location"><a href="#">Crate actix_session</a></h2><div class="sidebar-elems"><ul class="block"><li class="version">Version 0.7.2</li><li><a id="all-types" href="all.html">All Items</a></li></ul><section><ul class="block"><li><a href="#modules">Modules</a></li><li><a href="#structs">Structs</a></li><li><a href="#enums">Enums</a></li><li><a href="#traits">Traits</a></li></ul></section></div></nav><main><div class="width-limiter"><nav class="sub"><form class="search-form"><span></span><input class="search-input" name="search" aria-label="Run search in the documentation" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"><div id="help-button" title="help" tabindex="-1"><a href="../help.html">?</a></div><div id="settings-menu" tabindex="-1"><a href="../settings.html" title="settings"><img width="22" height="22" alt="Change settings" src="../static.files/wheel-7b819b6101059cd0.svg"></a></div></form></nav><section id="main-content" class="content"><div class="main-heading"><h1>Crate <a class="mod" href="#">actix_session</a><button id="copy-path" title="Copy item path to clipboard"><img src="../static.files/clipboard-7571035ce49a181d.svg" width="19" height="18" alt="Copy item path"></button></h1><span class="out-of-band"><a class="src" href="../src/actix_session/lib.rs.html#1-733">source</a> · <button id="toggle-all-docs" title="collapse all docs">[<span>−</span>]</button></span></div><details class="toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><p>Session management for Actix Web.</p>
|
||
<p>The HTTP protocol, at a first glance, is stateless: the client sends a request, the server
|
||
parses its content, performs some processing and returns a response. The outcome is only
|
||
influenced by the provided inputs (i.e. the request content) and whatever state the server
|
||
queries while performing its processing.</p>
|
||
<p>Stateless systems are easier to reason about, but they are not quite as powerful as we need them
|
||
to be - e.g. how do you authenticate a user? The user would be forced to authenticate <strong>for
|
||
every single request</strong>. That is, for example, how ‘Basic’ Authentication works. While it may
|
||
work for a machine user (i.e. an API client), it is impractical for a person—you do not want a
|
||
login prompt on every single page you navigate to!</p>
|
||
<p>There is a solution - <strong>sessions</strong>. Using sessions the server can attach state to a set of
|
||
requests coming from the same client. They are built on top of cookies - the server sets a
|
||
cookie in the HTTP response (<code>Set-Cookie</code> header), the client (e.g. the browser) will store the
|
||
cookie and play it back to the server when sending new requests (using the <code>Cookie</code> header).</p>
|
||
<p>We refer to the cookie used for sessions as a <strong>session cookie</strong>. Its content is called
|
||
<strong>session key</strong> (or <strong>session ID</strong>), while the state attached to the session is referred to as
|
||
<strong>session state</strong>.</p>
|
||
<p><code>actix-session</code> provides an easy-to-use framework to manage sessions in applications built on
|
||
top of Actix Web. <a href="struct.SessionMiddleware.html" title="struct actix_session::SessionMiddleware"><code>SessionMiddleware</code></a> is the middleware underpinning the functionality
|
||
provided by <code>actix-session</code>; it takes care of all the session cookie handling and instructs the
|
||
<strong>storage backend</strong> to create/delete/update the session state based on the operations performed
|
||
against the active <a href="struct.Session.html" title="struct actix_session::Session"><code>Session</code></a>.</p>
|
||
<p><code>actix-session</code> provides some built-in storage backends: (<a href="storage/struct.CookieSessionStore.html" title="struct actix_session::storage::CookieSessionStore"><code>CookieSessionStore</code></a>,
|
||
<a href="storage/struct.RedisSessionStore.html" title="struct actix_session::storage::RedisSessionStore"><code>RedisSessionStore</code></a>, and <a href="storage/struct.RedisActorSessionStore.html" title="struct actix_session::storage::RedisActorSessionStore"><code>RedisActorSessionStore</code></a>) - you can create a custom storage backend
|
||
by implementing the <a href="storage/trait.SessionStore.html" title="trait actix_session::storage::SessionStore"><code>SessionStore</code></a> trait.</p>
|
||
<p>Further reading on sessions:</p>
|
||
<ul>
|
||
<li><a href="https://datatracker.ietf.org/doc/html/rfc6265">RFC6265</a>;</li>
|
||
<li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html">OWASP’s session management cheat-sheet</a>.</li>
|
||
</ul>
|
||
<h2 id="getting-started"><a href="#getting-started">Getting started</a></h2>
|
||
<p>To start using sessions in your Actix Web application you must register <a href="struct.SessionMiddleware.html" title="struct actix_session::SessionMiddleware"><code>SessionMiddleware</code></a>
|
||
as a middleware on your <code>App</code>:</p>
|
||
|
||
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>actix_web::{web, App, HttpServer, HttpResponse, Error};
|
||
<span class="kw">use </span>actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
|
||
<span class="kw">use </span>actix_web::cookie::Key;
|
||
|
||
<span class="attr">#[actix_web::main]
|
||
</span><span class="kw">async fn </span>main() -> std::io::Result<()> {
|
||
<span class="comment">// The secret key would usually be read from a configuration file/environment variables.
|
||
</span><span class="kw">let </span>secret_key = Key::generate();
|
||
<span class="kw">let </span>redis_connection_string = <span class="string">"127.0.0.1:6379"</span>;
|
||
HttpServer::new(<span class="kw">move </span>||
|
||
App::new()
|
||
<span class="comment">// Add session management to your application using Redis for session state storage
|
||
</span>.wrap(
|
||
SessionMiddleware::new(
|
||
RedisActorSessionStore::new(redis_connection_string),
|
||
secret_key.clone()
|
||
)
|
||
)
|
||
.default_service(web::to(|| HttpResponse::Ok())))
|
||
.bind((<span class="string">"127.0.0.1"</span>, <span class="number">8080</span>))<span class="question-mark">?
|
||
</span>.run()
|
||
.<span class="kw">await
|
||
</span>}</code></pre></div>
|
||
<p>The session state can be accessed and modified by your request handlers using the <a href="struct.Session.html" title="struct actix_session::Session"><code>Session</code></a>
|
||
extractor. Note that this doesn’t work in the stream of a streaming response.</p>
|
||
|
||
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>actix_web::Error;
|
||
<span class="kw">use </span>actix_session::Session;
|
||
|
||
<span class="kw">fn </span>index(session: Session) -> <span class="prelude-ty">Result</span><<span class="kw-2">&</span><span class="lifetime">'static </span>str, Error> {
|
||
<span class="comment">// access the session state
|
||
</span><span class="kw">if let </span><span class="prelude-val">Some</span>(count) = session.get::<i32>(<span class="string">"counter"</span>)<span class="question-mark">? </span>{
|
||
<span class="macro">println!</span>(<span class="string">"SESSION value: {}"</span>, count);
|
||
<span class="comment">// modify the session state
|
||
</span>session.insert(<span class="string">"counter"</span>, count + <span class="number">1</span>)<span class="question-mark">?</span>;
|
||
} <span class="kw">else </span>{
|
||
session.insert(<span class="string">"counter"</span>, <span class="number">1</span>)<span class="question-mark">?</span>;
|
||
}
|
||
|
||
<span class="prelude-val">Ok</span>(<span class="string">"Welcome!"</span>)
|
||
}</code></pre></div>
|
||
<h2 id="choosing-a-backend"><a href="#choosing-a-backend">Choosing A Backend</a></h2>
|
||
<p>By default, <code>actix-session</code> does not provide any storage backend to retrieve and save the state
|
||
attached to your sessions. You can enable:</p>
|
||
<ul>
|
||
<li>
|
||
<p>a purely cookie-based “backend”, <a href="storage/struct.CookieSessionStore.html" title="struct actix_session::storage::CookieSessionStore"><code>CookieSessionStore</code></a>, using the <code>cookie-session</code> feature
|
||
flag.</p>
|
||
<div class="example-wrap"><pre class="language-toml"><code>[dependencies]
|
||
# ...
|
||
actix-session = { version = "...", features = ["cookie-session"] }
|
||
</code></pre></div></li>
|
||
<li>
|
||
<p>a Redis-based backend via <a href="https://docs.rs/actix-redis"><code>actix-redis</code></a>,
|
||
<a href="storage/struct.RedisActorSessionStore.html" title="struct actix_session::storage::RedisActorSessionStore"><code>RedisActorSessionStore</code></a>, using the <code>redis-actor-session</code> feature flag.</p>
|
||
<div class="example-wrap"><pre class="language-toml"><code>[dependencies]
|
||
# ...
|
||
actix-session = { version = "...", features = ["redis-actor-session"] }
|
||
</code></pre></div></li>
|
||
<li>
|
||
<p>a Redis-based backend via <a href="https://docs.rs/redis-rs"><code>redis-rs</code></a>, <a href="storage/struct.RedisSessionStore.html" title="struct actix_session::storage::RedisSessionStore"><code>RedisSessionStore</code></a>, using
|
||
the <code>redis-rs-session</code> feature flag.</p>
|
||
<div class="example-wrap"><pre class="language-toml"><code>[dependencies]
|
||
# ...
|
||
actix-session = { version = "...", features = ["redis-rs-session"] }
|
||
</code></pre></div>
|
||
<p>Add the <code>redis-rs-tls-session</code> feature flag if you want to connect to Redis using a secured
|
||
connection:</p>
|
||
<div class="example-wrap"><pre class="language-toml"><code>[dependencies]
|
||
# ...
|
||
actix-session = { version = "...", features = ["redis-rs-session", "redis-rs-tls-session"] }
|
||
</code></pre></div></li>
|
||
</ul>
|
||
<p>You can implement your own session storage backend using the <a href="storage/trait.SessionStore.html" title="trait actix_session::storage::SessionStore"><code>SessionStore</code></a> trait.</p>
|
||
</div></details><h2 id="modules" class="small-section-header"><a href="#modules">Modules</a></h2><ul class="item-table"><li><div class="item-name"><a class="mod" href="config/index.html" title="mod actix_session::config">config</a></div><div class="desc docblock-short">Configuration options to tune the behaviour of <a href="struct.SessionMiddleware.html" title="struct actix_session::SessionMiddleware"><code>SessionMiddleware</code></a>.</div></li><li><div class="item-name"><a class="mod" href="storage/index.html" title="mod actix_session::storage">storage</a></div><div class="desc docblock-short">Pluggable storage backends for session state.</div></li></ul><h2 id="structs" class="small-section-header"><a href="#structs">Structs</a></h2><ul class="item-table"><li><div class="item-name"><a class="struct" href="struct.Session.html" title="struct actix_session::Session">Session</a></div><div class="desc docblock-short">The primary interface to access and modify session state.</div></li><li><div class="item-name"><a class="struct" href="struct.SessionGetError.html" title="struct actix_session::SessionGetError">SessionGetError</a></div><div class="desc docblock-short">Error returned by <a href="struct.Session.html#method.get" title="method actix_session::Session::get"><code>Session::get</code></a>.</div></li><li><div class="item-name"><a class="struct" href="struct.SessionInsertError.html" title="struct actix_session::SessionInsertError">SessionInsertError</a></div><div class="desc docblock-short">Error returned by <a href="struct.Session.html#method.insert" title="method actix_session::Session::insert"><code>Session::insert</code></a>.</div></li><li><div class="item-name"><a class="struct" href="struct.SessionMiddleware.html" title="struct actix_session::SessionMiddleware">SessionMiddleware</a></div><div class="desc docblock-short">A middleware for session management in Actix Web applications.</div></li></ul><h2 id="enums" class="small-section-header"><a href="#enums">Enums</a></h2><ul class="item-table"><li><div class="item-name"><a class="enum" href="enum.SessionStatus.html" title="enum actix_session::SessionStatus">SessionStatus</a></div><div class="desc docblock-short">Status of a <a href="struct.Session.html" title="struct actix_session::Session"><code>Session</code></a>.</div></li></ul><h2 id="traits" class="small-section-header"><a href="#traits">Traits</a></h2><ul class="item-table"><li><div class="item-name"><a class="trait" href="trait.SessionExt.html" title="trait actix_session::SessionExt">SessionExt</a></div><div class="desc docblock-short">Extract a <a href="struct.Session.html" title="struct actix_session::Session"><code>Session</code></a> object from various <code>actix-web</code> types (e.g. <code>HttpRequest</code>,
|
||
<code>ServiceRequest</code>, <code>ServiceResponse</code>).</div></li></ul></section></div></main></body></html> |