如何在Rocket框架中使用Fairing拒绝传入请求?
直接用Fairing拦截请求
你可以在on_request方法中检查Cookie是否存在,若不存在则直接构造响应并终止后续路由处理。修改后的代码如下:
use rocket::{Request, Data, Response, fairing::{Fairing, Info, Kind}, http::{Status, Cookie}}; #[rocket::async_trait] impl Fairing for LoginCheck { fn info(&self) -> Info { Info { name: "Login Check", kind: Kind::Request | Kind::Response, } } async fn on_request(&self, request: &mut Request<'_>, _: &mut Data<'_>) { // 检查请求是否携带auth Cookie if request.cookies().get("auth").is_none() { // 构建401未授权响应 let mut response = Response::new(); response.set_status(Status::Unauthorized); response.set_body("Missing authentication cookie"); // 设置响应,终止后续路由处理流程 request.set_response(response); } } async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) { response.set_header(Cookie::new("auth", "test cookie")); } }
当auth Cookie不存在时,Rocket会直接返回你构建的401响应,不会继续执行后续的路由处理器。
替代方案:使用Rocket守卫(Guard)
如果你不需要对所有请求做全局检查,或者想更模块化地处理认证逻辑,Rocket的**守卫(Guard)**是更合适的选择。它可以针对特定路由或路由组做前置检查:
1. 定义认证守卫
use rocket::request::{FromRequest, Outcome}; use rocket::http::Status; // 空结构体作为守卫标识 struct AuthGuard; #[rocket::async_trait] impl<'r> FromRequest<'r> for AuthGuard { type Error = (); async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> { // 检查Cookie是否存在 if request.cookies().get("auth").is_some() { Outcome::Success(AuthGuard) } else { // 验证失败时返回401 Outcome::Failure((Status::Unauthorized, ())) } } }
2. 在路由中使用守卫
#[get("/protected")] async fn protected_route(_guard: AuthGuard) -> &'static str { "This is a protected route only accessible with auth cookie" }
只有携带auth Cookie的请求才能访问该路由,未携带的请求会自动返回401未授权响应。如果要全局应用,可以将守卫添加到所有路由或路由组上。
内容的提问来源于stack exchange,提问作者Vasu Subbannavar
相关产品推荐
相关产品推荐

