Extension for actix-web to validate user permissions

Overview

actix-web-grants

Extension for actix-web to validate user permissions.

CI 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 (like actix-web-httpauth).

Example of proc-macro way protection

use actix_web_grants::proc_macro::{has_permissions};

#[get("/secure")]
#[has_permissions("OP_READ_SECURED_INFO")]
async fn macro_secured() -> HttpResponse {
    HttpResponse::Ok().body("ADMIN_RESPONSE")
}

Example of Guard way protection

use actix_web_grants::{PermissionGuard, GrantsMiddleware};

App::new()
    .wrap(GrantsMiddleware::with_extractor(extract))
    .service(web::resource("/admin")
            .to(|| async { HttpResponse::Ok().finish() })
            .guard(PermissionGuard::new("ROLE_ADMIN".to_string())))

Example of manual way protection

use actix_web_grants::permissions::{AuthDetails, PermissionsCheck};

async fn manual_secure(details: AuthDetails) -> HttpResponse {
    if details.has_permission(ROLE_ADMIN) {
        return HttpResponse::Ok().body("ADMIN_RESPONSE");
    }
    HttpResponse::Ok().body("OTHER_RESPONSE")
}

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

Comments
  • 404 instead of 403 for Scope

    404 instead of 403 for Scope

    I know it's not a documented use case, but it works and somehow returns 404 error instead of 403.

    .service(
        web::scope("/admin")
            .service(index)
            .service(users)
            .guard(PermissionGuard::new(ROLE_ADMIN.to_string()))
    );
    

    Was checked on v3.0.0-beta.1

    documentation question research 
    opened by RoDmitry 22
  • Remove arc and refcell

    Remove arc and refcell

    Description:

    I've looked at actix-identity middleware and I think that arc and refcell is not needed. I might be wrong, I'm still learning, but all tests have passed. And what the attache was for? Do you use it elsewhere?

    Checklist:

    • [ ] Tests for the changes have been added (for bug fixes / features);
    • [ ] Docs have been added / updated (for bug fixes / features).
    • [ ] This PR has been added to CHANGELOG.md (to [Unreleased] section);
    opened by RoDmitry 10
  • Using HttpAuthentication wrapper on the same named scope but different handler

    Using HttpAuthentication wrapper on the same named scope but different handler

    Thank you for the amazing package! This is more of a question than an issue.

    I've been following the jwt-httpauth example:

    let auth = HttpAuthentication::bearer(validator);
    App::new().service(create_token).service(
        web::scope("/api")
            .wrap(auth)
            .service(permission_secured)
            .service(manager_secured),
    )
    

    The unguarded create_token handler is outside the /api scope. The problem arises when you want to nest the unguarded route inside /api:

    App::new()
        .service(
            web::scope("/api/v1")
                .wrap(HttpAuthentication::bearer(validator))
                .service(
                    web::scope("/reservations")
                        .configure(reservations_controllers::secured_routes),
                ),
        )
        .service(
            web::scope("/api/v1")
                .service(web::scope("/auth").configure(auth_controller::routes)),
        )
        .app_data(data.clone())
    

    Here, the first route works, but the second one returns 401. Adding regexp {regex:$|/.*?} on the second scope doesn't work either.

    Is there a way to achieve this? (Other than wrapping the handlers individually)

    opened by stevenfukase 7
  • Error

    Error "type `Config` is not a member of trait `FromRequest`"

    When I try to use "actix-web-grants" I get the following error:

    error[E0437]: type Config is not a member of trait FromRequest --> C:\Users\myuser.cargo\registry\src\github.com-1ecc6299db9ec823\actix-web-grants-3.0.0-beta.3\src\permissions\mod.rs:92:5

    What could be the reason to get this error?

    question wait 
    opened by maku 7
  • Let `PermissionsExtractor::extract` receive a `&mut ServiceRequest` so extractors can actually access the inner `HttpRequest`

    Let `PermissionsExtractor::extract` receive a `&mut ServiceRequest` so extractors can actually access the inner `HttpRequest`

    As far as I can tell, the only way to get a hold of a ServiceRequest's inner HttpRequest is through into_parts, which takes self and parts_mut, which takes &mut self. Since actix-web-grants hands you a &ServiceRequest, this HttpRequest is therefore inaccessible, limiting the usefulness.

    enhancement feature 
    opened by alexschrod 6
  • Wrap proc-macroed function body in closure

    Wrap proc-macroed function body in closure

    Description:

    Make ?-operator and early returning work as expected in functions with the #[has_permissions("foo")] attribute. This simply wraps the function body in a closure with an async block whis is immediately called and awaited. I believe that probably makes this a breaking change?

    It should probably be noted that I have never played with the implementation of proc macros before...

    Checklist:

    • [x] Tests for the changes have been added (for bug fixes / features);
    • [ ] Docs have been added / updated (for bug fixes / features).
    • [ ] This PR has been added to CHANGELOG.md (to [Unreleased] section);

    Closes #3

    opened by usbalbin 6
  • Migrating to actix 4

    Migrating to actix 4

    Description: migrating to newest actix-web

    Checklist:

    • [x] Tests for the changes have been added (for bug fixes / features);
    • [x] Docs have been added / updated (for bug fixes / features).
    • [x] This PR has been added to CHANGELOG.md (to [Unreleased] section);
    wait 
    opened by augustocdias 5
  • Check user name in route

    Check user name in route

    Hello, first of all thanks for your nice and simple to use crate!

    Is it possible, to check the login user name in a route? I have only seen that AuthDetails has only a permissions value.

    I ask because I would like to implement a function that a user can change his credentials, but for that I have to be sure, that the user can only change his own ones, and not from other users.

    question 
    opened by jb-alvarado 4
  • Fails to build against actix_web 4.0.0-beta.14

    Fails to build against actix_web 4.0.0-beta.14

    After trying to update to beta.14, I get the following error. The second one looks like a quick fix. Not so sure about the first one.

    error[E0599]: no method named `extensions` found for reference `&RequestHead` in the current scope
      --> /home/.cargo/git/checkouts/actix-web-grants-fc366f5a984b4e1f/f2f9964/src/guards.rs:44:14
       |
    44 |             .extensions()
       |              ^^^^^^^^^^ method not found in `&RequestHead`
    
    error[E0599]: no method named `extensions` found for struct `HttpRequest` in the current scope
      --> /home/.cargo/git/checkouts/actix-web-grants-fc366f5a984b4e1f/f2f9964/src/permissions/mod.rs:97:17
       |
    97 |             req.extensions()
       |                 ^^^^^^^^^^ method not found in `HttpRequest`
       |
      ::: /home/.cargo/registry/src/github.com-1ecc6299db9ec823/actix-http-3.0.0-beta.15/src/http_message.rs:29:8
       |
    29 |     fn extensions(&self) -> Ref<'_, Extensions>;
       |        ---------- the method is available for `HttpRequest` here
       |
       = help: items from traits can only be used if the trait is in scope
    help: the following trait is implemented but not in scope; perhaps add a `use` for it:
       |
    16 | use actix_web::HttpMessage;
    

    I have reverted to an old Cargo.lock file which I'll stay with for now.

    opened by tl8roy 4
  • Validator issue

    Validator issue

    Hi there, seems that the old exaple does not compile due to mismatch return types, specifically here: https://github.com/DDtKey/actix-web-grants/blob/92d97c9bebb4b42beff62e829ca6b3e64edbb75b/examples/jwt-httpauth/src/main.rs#L50

    question 
    opened by maxidev 3
  • Change Arc to Rc in middleware

    Change Arc to Rc in middleware

    Description:

    Checklist:

    • [ ] Tests for the changes have been added (for bug fixes / features);
    • [ ] Docs have been added / updated (for bug fixes / features).
    • [ ] This PR has been added to CHANGELOG.md (to [Unreleased] section);
    opened by RoDmitry 3
  • use enum in attribute?

    use enum in attribute?

    Hi,

    Is it possible to use an enum value in the has_permissions attribute at all? I understand that what i have below is not valid syntax but want to understand if something like this is possible?

    from:

    #[has_permissions("CanRead")]
    

    to:

    #[has_permissions(Permissions::CanRead.to_string())]
    
    enhancement question 
    opened by peteringram0 2
Releases(3.0.1)
Owner
Artem Medvedev
Software Engineer
Artem Medvedev
Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

Actix Web Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust Features Supports HTTP/1.x and HTTP/2 Streaming and pipelining

Actix 16.3k Jan 8, 2023
A starter template for actix-web projects that feels very Django-esque. Avoid the boring stuff and move faster.

Jelly A.K.A, the actix-web starter you probably wish you had. This is provided as-is, and anyone is free to extend it or rework it as they desire - ju

SecretKeys 198 Dec 15, 2022
Add Facebook and Google authentication to your HTTP REST API in Actix-web

I created this project while learning Rust. Project shows how to handle Facebook and Google token verification in Rust using Actix-Web. Hope this help

null 37 Dec 31, 2022
In-progress extractors and middleware for Actix Web

actix-web-lab Experimental extractors, middleware, and other extras for possible inclusion in Actix Web. Things To Know About This Crate It will never

Rob Ede 51 Dec 20, 2022
Easy to use multipart forms for actix-web

Actix Easy Multipart Easy to use Multipart Forms for actix-web. File uploads are written to disk as temporary files similar to the way the $_FILES var

Jacob Halsey 17 Jan 3, 2023
Example Blog using Rust, Actix Web, HTMX, Mustache

Actix Blog An example blog built with Actix. It uses htmx and handlebar templates. Running To run the blog, you need to have a recent version of Rust

Dru Jensen 2 Nov 11, 2022
Actix-web wrapper for garde, a Rust validation library.

Garde-actix-web   Actix-web wrapper for garde, a Rust validation library. Installation Usage example Feature flags About us Installation [dependencies

Netwo 5 Sep 8, 2023
Static Web Server - a very small and fast production-ready web server suitable to serve static web files or assets

Static Web Server (or SWS abbreviated) is a very small and fast production-ready web server suitable to serve static web files or assets.

Jose Quintana 496 Jan 2, 2023
Example Actix 2.x REST application implementing many features

Rust/Actix Example An Actix 2.0 REST server using the Rust language. Motivation Actix Web is a fast, powerful web framework for building web applicati

David D. 238 Dec 31, 2022
Basic Actix + Diesel + Postgres REST API

Actix-Crud Basic Actix + Diesel + Postgres REST API Setup Install and setup PostgreSQL Set DATABASE_URL environment variable or specify in .env file g

Aathif Naseer 4 Sep 23, 2022
Cookiecutter Rust Actix template for jumpstarting production-ready projects quickly.

Cookiecutter actix simple clean architecture This is a reusable Rust Cookiecutter template. The project is based on Actix web in combination with Dies

Microsoft 19 Feb 12, 2023
Fahrenheit-celsius converter using actix

fahrenheit-celsius-converter Simple http Fahrenheit/Celsius/Kelvin converter using actix-web. Note This is a toy project, not yet finished. It's not r

null 5 Nov 7, 2023
A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code. :zap::crab:

binserve âš¡ ?? A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code. ?? UPDATE: N

Mufeed VH 722 Dec 27, 2022
Simple and fast web server

see Overview Simple and fast web server as a single executable with no extra dependencies required. Features Built with Tokio and Hyper TLS encryption

null 174 Dec 9, 2022
A flexible web framework that promotes stability, safety, security and speed.

A flexible web framework that promotes stability, safety, security and speed. Features Stability focused. All releases target stable Rust. This will n

Gotham 2.1k Jan 3, 2023
JSON Web Token implementation in Rust.

Frank JWT Implementation of JSON Web Tokens in Rust. Algorithms and features supported HS256 HS384 HS512 RS256 RS384 RS512 ES256 ES384 ES512 Sign Veri

Alex Maslakov 246 Dec 27, 2022
An Extensible, Concurrent Web Framework for Rust

Iron Extensible, Concurrency Focused Web Development in Rust. Response Timer Example Note: This example works with the current iron code in this repos

null 6.1k Dec 27, 2022
An expressjs inspired web framework for Rust

nickel.rs nickel.rs is a simple and lightweight foundation for web applications written in Rust. Its API is inspired by the popular express framework

null 3k Jan 3, 2023
A web framework for Rust.

Rocket Rocket is an async web framework for Rust with a focus on usability, security, extensibility, and speed. #[macro_use] extern crate rocket; #[g

Sergio Benitez 19.5k Jan 8, 2023