actix-webで保護されたルートを設定する方法

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
}

このコードは、3つのルート(/login、/logout、/protected)を含む単純な actix-web アプリを作成します。/login ルートはユーザーのログインに、/logout ルートはユーザーのログアウトに使用され、/protected ルートは保護されたルートで、ログインしているユーザーのみがアクセスできます。

メイン関数では、IdentityService::new メソッドの呼び出しで認証サービスを設定し、認証ポリシーとして CookieIdentityPolicy を使用します。このポリシーは、32 バイトのランダム値を暗号鍵として使用し、認証情報を Cookie に格納します。

ログイン関数では、identity.rememberメソッドを使ってユーザーIDを任意の値に設定し、ユーザーがログイン中であることを示します。ログアウト関数では、identity.forgetメソッドを使ってユーザーIDをNoneに設定し、ユーザーがログアウト中であることを示します。

protected_route 関数では、まずユーザーがログインしているか確認し、ログインしていればユーザー識別子を伴ったレスポンスを返します。そうでない場合、認証されていないレスポンスを返します。

  1. カーゴラン
  2. ネイティブな日本語にとらわれずにパラフレーズをお願いします。http://localhost:8080/protected
  3. http://localhost:8080/login にアクセスしてください。
  4. http://localhost:8080/protected

提示のコードはあくまで、actix-webで保護されたルートを作成するデモのため、基本的な例を提供していることに注意してください。実際のアプリケーションでは、より複雑な認証および認可の仕組みが必要になる場合があります。

bannerAds