温馨提示×

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

小云
116
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