| Crates.io | protect-salvo |
| lib.rs | protect-salvo |
| version | 0.2.0 |
| created_at | 2024-04-10 17:59:54.434953+00 |
| updated_at | 2025-01-06 00:02:57.633043+00 |
| description | Authorization extension `salvo` to protect your endpoints |
| homepage | https://github.com/DDtKey/protect-endpoints |
| repository | https://github.com/DDtKey/protect-endpoints |
| max_upload_size | |
| id | 1203834 |
| size | 45,059 |
Authorization extension for
salvoto protect your endpoints.
To check user access to specific services, you can use built-in proc-macro or manual.
The library can also be integrated with third-party solutions (e.g. jwt-middlewares).
The easiest way is to declare a function with the following signature (trait is already implemented for such Fn):
use salvo::prelude::*;
// You can use custom type instead of String
// It requires to use hyper's `Request` & `Response` types, because integration is based on `tower`
pub async fn extract(req: &mut salvo::hyper::Request<ReqBody>) -> Result<HashSet<String>, salvo::hyper::Response<ResBody>>
// You can use [`salvo_extra`] directly for Tower compatibility or re-exported one
use protect_salvo::salvo_extra::TowerLayerCompat;
Router::with_path("/")
.hoop(GrantsLayer::with_extractor(extract).compat())
.push(Router::with_path("/endpoint").get(your_handler))
Steps 2 and 3 can be replaced by custom middleware or integration with another libraries.
proc-macro way protection#[protect_salvo::protect("ROLE_ADMIN")]
#[handler]
async fn macro_secured() -> &'static str {
return "Hello, World!";
}
Here is an example using the ty and expr attributes. But these are independent features.
expr allows you to include some checks in the macro based on function params, it can be combined with authorities by
using all/any.
ty allows you to use a custom type for th authorities (then the middleware needs to be configured).
use enums::Role::{self, ADMIN};
use dto::User;
#[post("/info/{user_id}")]
#[protect_salvo::protect(any("ADMIN", expr = "user.is_super_user()"), ty = "Role")]
async fn admin_or_super_user(user: User) -> &'static str {
"some secured response"
}
use protect_salvo::authorities::{AuthDetails, AuthoritiesCheck};
async fn manual_secure(details: AuthDetails) -> &'static str {
if details.has_authority(ROLE_ADMIN) {
return "ADMIN_RESPONSE";
}
"OTHER_RESPONSE"
}
You can find more examples in the git repository folder and documentation.
salvo versionsprotect-salvo: 0.1.* supported version of salvo is 0.70.*protect-salvo: 0.2.* supported version of salvo is 0.75.*