1
0
mirror of https://github.com/actix/examples synced 2024-11-23 14:31:07 +01:00

improve prod advice in cookie-auth

This commit is contained in:
Rob Ede 2023-01-03 14:04:10 +00:00
parent b951c4dbee
commit de5e6eecc0
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
3 changed files with 44 additions and 21 deletions

2
Cargo.lock generated
View File

@ -2050,7 +2050,9 @@ dependencies = [
"actix-identity", "actix-identity",
"actix-session", "actix-session",
"actix-web", "actix-web",
"actix-web-lab",
"env_logger", "env_logger",
"log",
"rand 0.8.5", "rand 0.8.5",
] ]

View File

@ -5,8 +5,10 @@ edition = "2021"
[dependencies] [dependencies]
actix-web.workspace = true actix-web.workspace = true
actix-web-lab.workspace = true
actix-identity.workspace = true actix-identity.workspace = true
actix-session = { workspace = true, features = ["cookie-session"] } actix-session = { workspace = true, features = ["cookie-session"] }
env_logger.workspace = true env_logger.workspace = true
log.workspace = true
rand.workspace = true rand.workspace = true

View File

@ -1,55 +1,74 @@
use actix_identity::{Identity, IdentityMiddleware}; use actix_identity::{Identity, IdentityMiddleware};
use actix_session::{storage::CookieSessionStore, SessionMiddleware}; use actix_session::{config::PersistentSession, storage::CookieSessionStore, SessionMiddleware};
use actix_web::{ use actix_web::{
cookie::Key, middleware, web, App, HttpMessage as _, HttpRequest, HttpResponse, HttpServer, cookie::{time::Duration, Key},
error,
http::StatusCode,
middleware, web, App, HttpMessage as _, HttpRequest, HttpServer, Responder,
}; };
async fn index(id: Identity) -> String { use actix_web_lab::web::Redirect;
format!(
"Hello {}", const ONE_MINUTE: Duration = Duration::minutes(1);
id.id().unwrap_or_else(|_| "Anonymous".to_owned())
) async fn index(identity: Option<Identity>) -> actix_web::Result<impl Responder> {
let id = match identity.map(|id| id.id()) {
None => "anonymous".to_owned(),
Some(Ok(id)) => id,
Some(Err(err)) => return Err(error::ErrorInternalServerError(err)),
};
Ok(format!("Hello {id}"))
} }
async fn login(req: HttpRequest) -> HttpResponse { async fn login(req: HttpRequest) -> impl Responder {
Identity::login(&req.extensions(), "user1".to_owned()).unwrap(); Identity::login(&req.extensions(), "user1".to_owned()).unwrap();
HttpResponse::Found() Redirect::to("/").using_status_code(StatusCode::FOUND)
.insert_header(("location", "/"))
.finish()
} }
async fn logout(id: Identity) -> HttpResponse { async fn logout(id: Identity) -> impl Responder {
id.logout(); id.logout();
HttpResponse::Found() Redirect::to("/").using_status_code(StatusCode::FOUND)
.insert_header(("location", "/"))
.finish()
} }
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info"); env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
env_logger::init();
// Generate a random secret key. Note that it is important to use a unique // Generate a random secret key. Note that it is important to use a unique
// secret key for every project. Anyone with access to the key can generate // secret key for every project. Anyone with access to the key can generate
// authentication cookies for any user! // authentication cookies for any user!
//
// If the secret key is read from a file or the environment, make sure it is generated securely.
// For example, a secure random key (in base64 format) can be generated with the OpenSSL CLI:
// ```
// openssl rand -base64 64
// ```
//
// Then decoded and used converted to a Key:
// ```
// let secret_key = Key::from(base64::decode(&private_key_base64).unwrap());
// ```
let secret_key = Key::generate(); let secret_key = Key::generate();
log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(move || { HttpServer::new(move || {
App::new() App::new()
.service(web::resource("/login").route(web::post().to(login)))
.service(web::resource("/logout").route(web::post().to(logout)))
.service(web::resource("/").route(web::get().to(index)))
.wrap(IdentityMiddleware::default()) .wrap(IdentityMiddleware::default())
.wrap( .wrap(
SessionMiddleware::builder(CookieSessionStore::default(), secret_key.clone()) SessionMiddleware::builder(CookieSessionStore::default(), secret_key.clone())
.cookie_name("auth-example".to_owned()) .cookie_name("auth-example".to_owned())
.cookie_secure(false) .cookie_secure(false)
.session_lifecycle(PersistentSession::default().session_ttl(ONE_MINUTE))
.build(), .build(),
) )
// enable logger - always register Actix Web Logger middleware last .wrap(middleware::NormalizePath::trim())
.wrap(middleware::Logger::default()) .wrap(middleware::Logger::default())
.service(web::resource("/login").route(web::post().to(login)))
.service(web::resource("/logout").to(logout))
.service(web::resource("/").route(web::get().to(index)))
}) })
.bind(("127.0.0.1", 8080))? .bind(("127.0.0.1", 8080))?
.run() .run()