actix_identity/lib.rs
1/*!
2Identity management for Actix Web.
3
4`actix-identity` can be used to track identity of a user across multiple requests. It is built
5on top of HTTP sessions, via [`actix-session`](https://docs.rs/actix-session).
6
7# Getting started
8To start using identity management in your Actix Web application you must register
9[`IdentityMiddleware`] and `SessionMiddleware` as middleware on your `App`:
10
11```no_run
12# use actix_web::web;
13use actix_web::{cookie::Key, App, HttpServer, HttpResponse};
14use actix_identity::IdentityMiddleware;
15use actix_session::{storage::RedisSessionStore, SessionMiddleware};
16
17#[actix_web::main]
18async fn main() {
19 // When using `Key::generate()` it is important to initialize outside of the
20 // `HttpServer::new` closure. When deployed the secret key should be read from a
21 // configuration file or environment variables.
22 let secret_key = Key::generate();
23
24 let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
25 .await
26 .unwrap();
27
28 HttpServer::new(move || {
29 App::new()
30 // Install the identity framework first.
31 .wrap(IdentityMiddleware::default())
32 // The identity system is built on top of sessions. You must install the session
33 // middleware to leverage `actix-identity`. The session middleware must be mounted
34 // AFTER the identity middleware: `actix-web` invokes middleware in the OPPOSITE
35 // order of registration when it receives an incoming request.
36 .wrap(SessionMiddleware::new(
37 redis_store.clone(),
38 secret_key.clone(),
39 ))
40 // Your request handlers [...]
41 # .default_service(web::to(|| HttpResponse::Ok()))
42 })
43# ;
44}
45```
46
47User identities can be created, accessed and destroyed using the [`Identity`] extractor in your
48request handlers:
49
50```no_run
51use actix_web::{get, post, HttpResponse, Responder, HttpRequest, HttpMessage};
52use actix_identity::Identity;
53use actix_session::storage::RedisSessionStore;
54
55#[get("/")]
56async fn index(user: Option<Identity>) -> impl Responder {
57 if let Some(user) = user {
58 format!("Welcome! {}", user.id().unwrap())
59 } else {
60 "Welcome Anonymous!".to_owned()
61 }
62}
63
64#[post("/login")]
65async fn login(request: HttpRequest) -> impl Responder {
66 // Some kind of authentication should happen here
67 // e.g. password-based, biometric, etc.
68 // [...]
69
70 // attach a verified user identity to the active session
71 Identity::login(&request.extensions(), "User1".into()).unwrap();
72
73 HttpResponse::Ok()
74}
75
76#[post("/logout")]
77async fn logout(user: Identity) -> impl Responder {
78 user.logout();
79 HttpResponse::Ok()
80}
81```
82
83# Advanced configuration
84By default, `actix-identity` does not automatically log out users. You can change this behaviour
85by customising the configuration for [`IdentityMiddleware`] via [`IdentityMiddleware::builder`].
86
87In particular, you can automatically log out users who:
88- have been inactive for a while (see [`IdentityMiddlewareBuilder::visit_deadline`]);
89- logged in too long ago (see [`IdentityMiddlewareBuilder::login_deadline`]).
90
91[`IdentityMiddlewareBuilder::visit_deadline`]: config::IdentityMiddlewareBuilder::visit_deadline
92[`IdentityMiddlewareBuilder::login_deadline`]: config::IdentityMiddlewareBuilder::login_deadline
93*/
94
95#![forbid(unsafe_code)]
96#![deny(missing_docs)]
97#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
98#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
99#![cfg_attr(docsrs, feature(doc_auto_cfg))]
100
101pub mod config;
102pub mod error;
103mod identity;
104mod identity_ext;
105mod middleware;
106
107pub use self::{identity::Identity, identity_ext::IdentityExt, middleware::IdentityMiddleware};