Expand description

Procedural macros for checking user authorities (permissions or roles).

§Examples

use actix_web::{web, get, HttpResponse};
use actix_web_grants::protect;
use actix_web::http::StatusCode;
use actix_web::body::BoxBody;

// User should be ADMIN with OP_GET_SECRET permission
#[protect("ROLE_ADMIN", "OP_GET_SECRET")]
async fn macro_secured() -> HttpResponse {
    HttpResponse::Ok().body("some secured info")
}

// User should be ADMIN and MANAGER
#[protect("ROLE_ADMIN", "ROLE_MANAGER")]
async fn role_macro_secured() -> HttpResponse {
    HttpResponse::Ok().body("some secured info")
}

// Custom access denied message.
#[protect("ADMIN", error = "access_denied")]
async fn role_access() -> HttpResponse {
    HttpResponse::Ok().body("some secured info")
}
// Non-admin role accessor will receive this response.
// The return type of the custom function must be `actix web::HttpResponse`.
fn access_denied() -> HttpResponse {
    HttpResponse::with_body(
        StatusCode::FORBIDDEN,
        BoxBody::new("This resource allowed only for ADMIN"),
    )
}

// Additional security condition to ensure the protection of the endpoint
#[protect("USER", expr = "user_id.into_inner() == user.id")]
#[get("/resource/{user_id}")]
async fn role_macro_secured_with_params(user_id: web::Path<i32>, user: web::Data<User>) -> HttpResponse {
    HttpResponse::Ok().body("some secured info with parameters")   
}
struct User { id: i32 }

// You own type is also supported (need to configure middleware for this type as well):
#[protect("Role::Admin", "Role::Manager", ty = "Role")]
async fn role_enum_macro_secured() -> HttpResponse {
    HttpResponse::Ok().body("some secured info")
}
#[derive(Eq, PartialEq, Hash)] // required bounds
enum Role { Admin, Manager }

Attribute Macros§

  • Macro to сheck that the user has all the specified permissions. Allow to add a conditional restriction based on handlers parameters. Add the expr attribute followed by the the boolean expression to validate based on parameters