1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
//! Authfix provides a quick and easy way to add authentication to your [Actix Web](https://docs.rs/actix-web/latest/actix_web/index.html) app.
//!
//! The [AuthToken] extractor enables straightforward access to the authenticated user in secured handlers.
//!
//! # Quick start
//! For a quick start, use the working examples from [authfix-examples](https://github.com/Hypnagokali/authfix-examples)
//!
//! # Session Authentication
//! Currently, only session authentication is supported (OIDC support is planned). This implementation is built on
//! [actix-session](https://docs.rs/actix-session/latest/actix_session/index.html). Authfix re-exports actix-session for this reason.
//!
//! The session authentication flow can be configured in two modes.
//!
//! 1. API based (default)
//! - It is designed to work with Single Page Applications, so it offers a JSON API for login, logout and mfa verification. Redirects
//! are then handled by the SPA.
//! 2. Redirect based
//! - Instead of returning 401 for unauthorized requests, it redirects the user to the login page. The login flow is completely handled by the browser.
//! You just have to define the login, mfa and logout pages. The redirects are going to the same routes as defined in [Routes](crate::session::config::Routes).
//! To activate this mode, set `with_redirect_flow()` in [SessionLoginAppBuilder](crate::session::app_builder::SessionLoginAppBuilder).
//!
//! # Async traits
//! To use this library, it is necessary to implement certrain traits (e.g.: [LoadUserByCredentials](crate::login::LoadUserByCredentials)).
//! Wherever possible, native async syntax is supported.
//!
//! However, some of the traits must be `dyn compatible`, so the [async_trait](https://crates.io/crates/async-trait) crate
//! is used for those (e.g. for [MfaHandleMfaRequest](crate::multifactor::config::HandleMfaRequest)).
//!
//! Authfix re-exports the [authfix::async_trait](crate::async_trait) macro.
//!
//! # Examples
//! ## Session based authentication
//! ```no_run
//! use actix_web::{HttpResponse, HttpServer, Responder, cookie::Key, get};
//! use authfix::{
//! AuthToken,
//! login::{LoadUserByCredentials, LoadUserError, LoginToken},
//! session::{AccountInfo, app_builder::SessionLoginAppBuilder},
//! };
//! use serde::{Deserialize, Serialize};
//!
//! // A user intended for session authentication must derive Serialize, and Deserialize.
//! #[derive(Serialize, Deserialize)]
//! struct User {
//! name: String,
//! }
//!
//! // AccountInfo trait is used for disabling the user or to lock the account
//! // The user is enabled by default
//! impl AccountInfo for User {}
//!
//! // Struct that handles the authentication
//! struct AuthenticationService;
//!
//! // LoadUsersByCredentials uses async_trait, so its needed when implementing the trait for AuthenticationService
//! // async_trait is re-exported by authfix.
//! impl LoadUserByCredentials for AuthenticationService {
//! type User = User;
//!
//! async fn load_user(&self, login_token: &LoginToken) -> Result<Self::User, LoadUserError> {
//! // load user by email logic and check password
//! // currently authfix does not provide hashing functions, you can use for example https://docs.rs/argon2/latest/argon2/
//! if login_token.email == "test@example.org" && login_token.password == "password" {
//! Ok(User {
//! name: "Johnny".to_owned(),
//! })
//! } else {
//! Err(LoadUserError::LoginFailed)
//! }
//! }
//! }
//!
//! // You have access to the user via the AuthToken extractor in secured routes.
//! #[get("/secured")]
//! async fn secured(auth_token: AuthToken<User>) -> impl Responder {
//! let user = auth_token.authenticated_user();
//! HttpResponse::Ok().json(&*user)
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//! let key = Key::generate();
//! HttpServer::new(move || {
//! // SessionLoginAppBuilder is the simplest way to create an App instance configured with session based authentication
//! // This default config registers handlers for: /login, /logout and /login/mfa.
//! SessionLoginAppBuilder::create(AuthenticationService, key.clone())
//! .build()
//! .service(secured)
//! })
//! .bind("127.0.0.1:7080")?
//! .run()
//! .await
//! }
//! ```
//!
//! ## Configure the session
//! ```no_run
//! use actix_web::{HttpResponse, HttpServer, Responder, cookie::Key, get, middleware::Logger};
//! use authfix::{
//! AuthToken,
//! login::{LoadUserByCredentials, LoadUserError, LoginToken},
//! session::{
//! AccountInfo,
//! actix_session::{
//! SessionMiddleware,
//! config::{PersistentSession, SessionLifecycle},
//! storage::CookieSessionStore,
//! },
//! app_builder::SessionLoginAppBuilder,
//! },
//! };
//! use serde::{Deserialize, Serialize};
//!
//! // A user intended for session authentication must derive or implement Serialize, and Deserialize.
//! #[derive(Serialize, Deserialize)]
//! struct User {
//! name: String,
//! }
//!
//! impl AccountInfo for User {}
//!
//! // Struct that handles the authentication
//! struct AuthenticationService;
//!
//! // LoadUsersByCredentials uses async_trait, so its needed when implementing the trait for AuthenticationService
//! // async_trait is re-exported by authfix.
//! impl LoadUserByCredentials for AuthenticationService {
//! type User = User;
//!
//! async fn load_user(&self, login_token: &LoginToken) -> Result<Self::User, LoadUserError> {
//! // load user by email logic and check password
//! // currently authfix does not provide hashing functions, you can use for example https://docs.rs/argon2/latest/argon2/
//! if login_token.email == "test@example.org" && login_token.password == "password" {
//! Ok(User {
//! name: "Johnny".to_owned(),
//! })
//! } else {
//! Err(LoadUserError::LoginFailed)
//! }
//! }
//! }
//!
//! // You have access to the user via the AuthToken extractor in secured routes.
//! #[get("/secured")]
//! async fn secured(auth_token: AuthToken<User>) -> impl Responder {
//! let user = auth_token.authenticated_user();
//! HttpResponse::Ok().json(&*user)
//! }
//!
//! pub fn session_config(key: Key) -> SessionMiddleware<CookieSessionStore> {
//! let persistent_session = PersistentSession::default();
//! let lc = SessionLifecycle::PersistentSession(persistent_session);
//! SessionMiddleware::builder(CookieSessionStore::default(), key)
//! .cookie_name("sessionId".to_string())
//! .cookie_http_only(true)
//! .cookie_same_site(actix_web::cookie::SameSite::Strict)
//! .cookie_secure(false)
//! .session_lifecycle(lc)
//! .build()
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//! let key = Key::generate();
//! HttpServer::new(move || {
//! // SessionLoginAppBuilder is the simplest way to create an App instance configured with session based authentication
//! SessionLoginAppBuilder::create_with_session_middleware(
//! AuthenticationService,
//! session_config(key.clone()),
//! )
//! // create App instance with build()
//! .build()
//! .wrap(Logger::default())
//! .service(secured)
//! })
//! .bind("127.0.0.1:7080")?
//! .run()
//! .await
//! }
//! ```
use ;
use UnauthorizedError;
use ;
// re-exports
/// Re-exported `async_trait` macro for use in trait definitions.
pub use async_trait;
/// Main component used by the middleware to handle the actual authentication mechanism
///
/// Its main responsibility is to attempt retrieving the logged-in user or respond with an [UnauthorizedError].
/// Additionally it is responsible for configuring special request (e.g. injecting services), such as for login or mfa.
///
/// Currently only [SessionAuthProvider](crate::session::session_auth::SessionAuthProvider) implements [AuthenticationProvider].
/// Extractor that holds the authenticated user.
///
/// Injecting [AuthToken] into an unsecured (public) route currently results in a 500 error.
///
/// # Example
/// ```no_run
/// use actix_web::{get, HttpResponse, Responder};
/// use authfix::AuthToken;
///
/// struct User {
/// email: String,
/// }
///
/// #[get("/secured-route")]
/// async fn secured_route(token: AuthToken<User>) -> impl Responder {
/// HttpResponse::Ok().body(format!(
/// "Request from user: {}",
/// token.authenticated_user().email
/// ))
/// }
/// ```
/// Extension to get the [AuthToken] from [HttpRequest]
/// ```no_run
/// use actix_web::HttpRequest;
/// use authfix::AuthTokenExt;
/// use serde::Deserialize;
/// #[derive(Deserialize)]
/// struct User {
/// email: String
/// }
///
/// fn some_function(req: actix_web::HttpRequest) -> bool {
/// req.auth_token::<User>().is_some()
/// }
/// ```