溫馨提示×

如何在actix-web中建立受保護的路由

小云
184
2023-09-26 08:46:46
欄目: 編程語言

在actix-web中建立受保護的路由可以通過以下步驟實現:

  1. 首先,您需要將actix-web和actix-identity添加到您的Cargo.toml文件中。在[dependencies]部分中添加以下行:
actix-web = "3.3.2"
actix-identity = "0.5.0"
  1. 創建一個新的main.rs文件并添加以下代碼:
use actix_web::{web, App, HttpResponse, HttpServer};
use actix_identity::{CookieIdentityPolicy, Identity, IdentityService};
use rand::Rng;
use std::collections::HashMap;
async fn login(identity: Identity) -> HttpResponse {
// 將用戶標識設置為任意值
identity.remember("user_id".to_owned());
HttpResponse::Ok().body("Logged in successfully")
}
async fn logout(identity: Identity) -> HttpResponse {
// 將用戶標識設置為None
identity.forget();
HttpResponse::Ok().body("Logged out successfully")
}
async fn protected_route(identity: Identity) -> HttpResponse {
// 檢查用戶是否已登錄
if let Some(user_id) = identity.identity() {
HttpResponse::Ok().body(format!("Protected route, user_id: {}", user_id))
} else {
HttpResponse::Unauthorized().body("Unauthorized")
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
// 設置身份驗證服務
.wrap(IdentityService::new(
CookieIdentityPolicy::new(&[0; 32])
.name("auth-cookie")
.secure(false), // 在開發環境中設為false
))
.route("/login", web::post().to(login))
.route("/logout", web::post().to(logout))
.route("/protected", web::get().to(protected_route))
})
.bind("127.0.0.1:8080")?
.run()
.await
}

以上代碼創建了一個簡單的actix-web應用程序,其中包含三個路由:/login,/logout/protected。 /login路由用于登錄用戶,/logout路由用于登出用戶,/protected路由是一個受保護的路由,只有已登錄的用戶才能訪問。

main函數中,我們通過調用IdentityService::new方法設置了身份驗證服務,并使用CookieIdentityPolicy作為身份驗證策略。該策略使用32字節的隨機值作為加密密鑰,并將身份驗證信息存儲在cookie中。

login函數中,我們使用identity.remember方法將用戶標識設置為任意值,表示用戶已登錄。在logout函數中,我們使用identity.forget方法將用戶標識設置為None,表示用戶已登出。

protected_route函數中,我們首先檢查用戶是否已登錄,如果已登錄,則返回帶有用戶標識的響應。否則,返回未經授權的響應。

  1. 運行應用程序:使用cargo run命令運行應用程序,并在瀏覽器中訪問http://localhost:8080/protected。您將看到一個未經授權的響應。接下來,訪問http://localhost:8080/login,您將看到一個已登錄成功的響應。最后,再次訪問http://localhost:8080/protected,您將看到一個受保護的路由,其中包含用戶標識。

請注意,上述代碼僅提供了基本的示例,以演示如何在actix-web中創建受保護的路由。在實際應用程序中,您可能需要更復雜的身份驗證和授權機制。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女