使用ActixWeb框架,实现基于Token的权限认证与授权,实现只限于特定权限范围的资源访问。具体步骤如下:
[dependencies]
actix-web = "3.3.2"
actix-rt = "2.3.0"
fn validator(
req: ServiceRequest,
credentials: BearerAuth,
) -> impl Future- {
let token = credentials.token().to_owned();
// 通过token获取用户信息
let user = validate_token(&token);
match user {
Ok(user) => {
req.extensions_mut().insert(user);
ok(req)
}
Err(_e) => err(ErrorUnauthorized("Invalid token")),
}
}
fn authorizer(scopes: Vec) -> impl Fn(&ServiceRequest) -> bool {
move |req: &ServiceRequest| -> bool {
let user = req.extensions().get::().unwrap();
// 判断用户是否有访问特定scope的权限
scopes.iter().any(|s| user.scopes.contains(s))
}
}
let auth_scope = vec!["read_users".to_owned(), "write_users".to_owned()];
let middleware = middleware::normalize();
let middleware = middleware
.wrap(CookieSession::signed(&[0; 32]).secure(false))
.wrap(AutoCompress::new(ContentEncoding::Br))
.wrap_fn(|req, srv| {
let fut = validator(req, BearerAuth::from(req.clone()));
future::Either::A(fut.and_then(|req| {
let auth_fn = authorizer(auth_scope.clone());
if auth_fn(&req) {
future::Either::A(srv.call(req))
} else {
future::Either::B(err(ErrorForbidden("Insufficient scope")))
}
}))
});
这样,只有当Token验证和权限认证都通过后,才会继续处理请求。在所需要进行权限验证的地方,只需要像下面这样使用auth_scope定义的中间件即可:
#[get("/users")]
async fn get_users(user: User) -> impl Responder {
// 访问需要权限的资源之前先验证是否有访问权限(auth_scope)
// 如果没有,则返回ErrorForbidden("Insufficient scope")
// 有权限则返回所需要的资源
}