poem-grants icon indicating copy to clipboard operation
poem-grants copied to clipboard

Authorization extension for poem to validate user permissions

poem-grants

poem-grants

Extension for poem to validate user permissions.

CI Crates.io Downloads Badge crates.io Documentation dependency status Apache 2.0 or MIT licensed

To check user access to specific services, you can use built-in proc-macro, PermissionGuard or manual.

The library can also be integrated with third-party solutions or your custom middlewares (like jwt-auth example).

Provides a complete analogue of the actix-web-grants.

NOTE: poem-openapi support is still in development.

How to use

  1. Declare your own permission extractor

The easiest way is to declare a function with the following signature (trait is already implemented for such Fn):

// You can use custom type instead of String
async fn extract(req: &poem::Request) -> poem::Result<Vec<String>>
  1. Add middleware to your application using the extractor defined in step 1
Route::new()
    .at("/endpoint", your_endpoint)
    .with(GrantsMiddleware::with_extractor(extract))

Steps 1 and 2 can be replaced by custom middleware or integration with another libraries. Take a look at an jwt-auth example

  1. Protect your endpoints in any convenient way from the examples below:

Example of proc-macro way protection

use poem::{Response, http::StatusCode};

#[poem_grants::has_permissions("OP_READ_SECURED_INFO")]
async fn macro_secured() -> Response {
    Response::builder().status(StatusCode::OK).body("ADMIN_RESPONSE")
}
Example of ABAC-like protection and custom permission type

Here is an example using the type and secure attributes. But these are independent features.

secure allows you to include some checks in the macro based on function params.

type allows you to use a custom type for the roles and permissions (then the middleware needs to be configured). Take a look at an enum-role example

use poem::{Response, http::StatusCode, web};
use enums::Role::{self, ADMIN};
use dto::User;

#[poem_grants::has_role("ADMIN", type = "Role", secure = "*user_id == user.id")]
async fn macro_secured(user_id: web::Path<i32>, user: web::Data<User>) -> Response {
    Response::builder().status(StatusCode::OK).body("some secured response")
}

Example of manual way protection

use poem::{Response, http::StatusCode};
use poem_grants::permissions::{AuthDetails, PermissionsCheck};

#[poem::handler]
async fn manual_secure(details: AuthDetails) -> Response {
    if details.has_permission("ROLE_ADMIN") {
        return Response::builder().status(StatusCode::OK).body("ADMIN_RESPONSE");
    }
    Response::builder().status(StatusCode::OK).body("OTHER_RESPONSE")
}

You can find more examples in the git repository folder and documentation.

Supported poem versions

  • For poem-grants: 1.* supported version of poem is 1.*