1
0
mirror of https://github.com/actix/examples synced 2024-11-27 16:02:57 +01:00

Demonstrate how to use random keys for sessions.

This commit is contained in:
Pieter Frenssen 2020-04-13 12:36:49 +03:00
parent d04f0c2e56
commit 83bf0015c8
4 changed files with 20 additions and 6 deletions

View File

@ -10,3 +10,4 @@ actix-web = "2.0.0"
actix-identity = "0.2.0"
actix-rt = "1.0.0"
env_logger = "0.7"
rand = "0.7.3"

View File

@ -1,6 +1,7 @@
use actix_identity::Identity;
use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use rand::Rng;
async fn index(id: Identity) -> String {
format!(
@ -24,10 +25,14 @@ async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
HttpServer::new(|| {
// 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]>();
HttpServer::new(move || {
App::new()
.wrap(IdentityService::new(
CookieIdentityPolicy::new(&[0; 32])
CookieIdentityPolicy::new(&private_key)
.name("auth-example")
.secure(false),
))

View File

@ -13,5 +13,6 @@ env_logger = "0.7"
serde = { version = "^1.0", features = ["derive"] }
actix-service = "1.0.0"
actix-http = "1.0.0"
rand = "0.7.3"
serde_json = "1.0.40"
time = "0.1.42"

View File

@ -11,6 +11,7 @@ use actix_web::{
web::{get, post, resource},
App, HttpResponse, HttpServer, Result,
};
use rand::Rng;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
@ -76,10 +77,15 @@ async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info,actix_redis=info");
env_logger::init();
HttpServer::new(|| {
// 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]>();
HttpServer::new(move || {
App::new()
// redis session middleware
.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32]))
.wrap(RedisSession::new("127.0.0.1:6379", &private_key))
// enable logger - always register actix-web Logger middleware last
.wrap(middleware::Logger::default())
.service(resource("/").route(get().to(index)))
@ -136,10 +142,11 @@ mod test {
// - set-cookie actix-session will be in response (session cookie #3)
// - response should be: {"counter": 0, "user_id": None}
let srv = test::start(|| {
let private_key = rand::thread_rng().gen::<[u8; 32]>();
let srv = test::start(move || {
App::new()
.wrap(
RedisSession::new("127.0.0.1:6379", &[0; 32])
RedisSession::new("127.0.0.1:6379", &private_key)
.cookie_name("test-session"),
)
.wrap(middleware::Logger::default())