1
0
mirror of https://github.com/actix/examples synced 2024-11-30 17:14:35 +01:00
examples/auth/cookie-auth/src/main.rs

60 lines
1.9 KiB
Rust
Raw Normal View History

2022-10-26 17:51:27 +02:00
use actix_identity::{Identity, IdentityMiddleware};
use actix_session::{storage::CookieSessionStore, SessionMiddleware};
use actix_web::{
cookie::Key, middleware, web, App, HttpMessage as _, HttpRequest, HttpResponse, HttpServer,
};
use rand::Rng;
2018-04-19 01:46:35 +02:00
2019-12-07 18:59:24 +01:00
async fn index(id: Identity) -> String {
2019-09-04 17:04:57 +02:00
format!(
"Hello {}",
2022-10-26 17:51:27 +02:00
id.id().unwrap_or_else(|_| "Anonymous".to_owned())
2019-09-04 17:04:57 +02:00
)
2018-04-19 01:46:35 +02:00
}
2022-10-26 17:51:27 +02:00
async fn login(req: HttpRequest) -> HttpResponse {
Identity::login(&req.extensions(), "user1".to_owned()).unwrap();
HttpResponse::Found()
.insert_header(("location", "/"))
.finish()
2018-04-19 01:46:35 +02:00
}
2019-12-07 18:59:24 +01:00
async fn logout(id: Identity) -> HttpResponse {
2022-10-26 17:51:27 +02:00
id.logout();
HttpResponse::Found()
.insert_header(("location", "/"))
.finish()
2018-04-19 01:46:35 +02:00
}
2020-09-12 17:49:45 +02:00
#[actix_web::main]
2019-12-07 18:59:24 +01:00
async fn main() -> std::io::Result<()> {
2019-03-10 06:08:08 +01:00
std::env::set_var("RUST_LOG", "actix_web=info");
2018-04-19 01:46:35 +02:00
env_logger::init();
// Generate a random 32 byte key. Note that it is important to use a unique
// private key for every project. Anyone with access to the key can generate
// authentication cookies for any user!
let private_key = rand::thread_rng().gen::<[u8; 32]>();
2022-10-26 17:51:27 +02:00
HttpServer::new(move || {
2018-05-08 20:08:43 +02:00
App::new()
2022-10-26 17:51:27 +02:00
.wrap(IdentityMiddleware::default())
.wrap(
SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&private_key))
.cookie_name("auth-example".to_owned())
.cookie_secure(false)
.build(),
)
2022-02-06 09:13:24 +01:00
// enable logger - always register Actix Web Logger middleware last
.wrap(middleware::Logger::default())
2019-03-10 06:08:08 +01:00
.service(web::resource("/login").route(web::post().to(login)))
.service(web::resource("/logout").to(logout))
.service(web::resource("/").route(web::get().to(index)))
2019-03-10 03:03:09 +01:00
})
2022-02-17 21:22:36 +01:00
.bind(("127.0.0.1", 8080))?
2019-12-25 17:48:33 +01:00
.run()
2019-12-07 18:59:24 +01:00
.await
2018-04-19 01:46:35 +02:00
}