Crates.io | rocket-grants |
lib.rs | rocket-grants |
version | 0.1.4 |
source | src |
created_at | 2022-02-23 17:03:35.011887 |
updated_at | 2024-03-31 19:19:14.413256 |
description | Authorization extension for `rocket` to protect your endpoints |
homepage | https://github.com/DDtKey/protect-endpoints |
repository | https://github.com/DDtKey/protect-endpoints |
max_upload_size | |
id | 537962 |
size | 96,017 |
Extension for
rocket
to authorize requests.
To check user access to specific endpoints, you can use built-in proc-macro
or do it manually.
The easiest way is to declare a function with the following signature:
// You can use custom type instead of String
async fn extract(req: &rocket::Request<'_>) -> Option<HashSet<String>>
rocket::build().mount("/api", rocket::routes![endpoint])
.attach(GrantsFairing::with_extractor_fn(|req| {
Box::pin(extract(req)) // example with a separate async function `extract`, but you can write a closure right here
}))
Steps 1 and 2 can be replaced by integration with your custom fairing.
proc-macro
way protection#[rocket_grants::protect("OP_READ_SECURED_INFO")]
#[rocket::get("/")]
async fn macro_secured() -> &'static str {
"ADMIN_RESPONSE"
}
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 the authority (then the fairing needs to be configured).
Take a look at an enum-role example
use enums::Role::{self, ADMIN};
use dto::User;
#[rocket_grants::protect("USER", expr = "user_id == user.id")]
#[rocket::post("/secure/<user_id>", data = "<user>")]
async fn role_macro_secured_with_params(user_id: i32, user: Json<User>) -> &'static str {
"some secured info with parameters"
}
#[rocket_grants::protect(any("ADMIN", expr = "user.is_super_user()"))]
#[rocket::post("/secure/admin/<user_id>", data = "<user>")]
async fn admin_or_super_user(user_id: i32, user: Json<User>) -> &'static str {
"some secured info with parameters"
}
use rocket_grants::authorities::{AuthDetails, AuthoritiesCheck};
#[rocket::get("/")]
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
.
Custom error responses can be specified using Rocket catchers. See the Rocket documentation for catchers.
You can set up custom responses for:
401 Unauthorized
- when it wasn't possible to obtain authorization data from the request in your extractor.
403 Forbidden
- when the permissions did not match the specified for the endpoint.
rocket
versionsrocket-grants: 0.1.*
supported version of rocket
is 0.5.*