A Rust crate for managing authentication and authorization with support for multi-tenant / B2B products, powered by PropelAuth

Related tags

Web programming rust
Overview

PropelAuth

Add authentication and authorization to your application.

This library is meant to be used with a PropelAuth account. You can sign up and get started for free.

Initialize

First, you'll need to initialize the library. You can either call PropelAuth::init or PropelAuth::fetch_and_init (which will fetch any unspecified metadata).

let auth = PropelAuth::fetch_and_init(AuthOptions {
    auth_url: "REPLACE_ME".to_string(),
    api_key: "REPLACE_ME".to_string(),
}).await.expect("Unable to initialize authentication");

Usage / Protecting APIs

Want us to add support for another framework? Reach out at [email protected]

Axum

To use Axum, make sure to enable the axum feature in your Cargo.toml.

Then, add PropelAuthLayer to your Router:

let auth_layer = PropelAuthLayer::new(auth);

let app = Router::new()
    .route("/whoami", get(whoami))
    .route("/org/:org_name/whoami", get(org_whoami))
    .layer(layer); // <-- here

You can then take User in as an argument, which will look for an access token in the Authorization header.

// User will automatically return a 401 (Unauthorized) if a valid access token wasn't provided
async fn whoami(user: User) -> String {
    user.user_id
}

You can also check which organizations the user is in, and which roles and permissions they have.

// If the user isn't in the provided organization, a 403 is returned
async fn org_whoami(user: User,
                    Path(org_name): Path<String>) -> Result<String, UnauthorizedOrForbiddenError> {
    let org = user.validate_org_membership(RequiredOrg::OrgName(&org_name),
                                           UserRequirementsInOrg::IsRole("Admin"))?;
    Ok(format!("You are a {} in {}", org.user_role, org.org_name))
}

You can also get the full auth struct and make API calls with it:

// Extension(auth) is useful for making API requests
async fn make_req(Extension(auth): Extension<Arc<PropelAuth>>) -> String {
    let magic_link = auth.user().create_magic_link(CreateMagicLinkRequest {
        email: "[email protected]".to_string(),
        ..Default::default()
    }).await.expect("Couldn't create magic link");
    magic_link.url
}

Actix

To use Actix, make sure to enable the actix4 feature in your Cargo.toml.

Add your PropelAuth to your Router:

let auth = PropelAuth::fetch_and_init(/*...*/)
//...
HttpServer::new(move || {
    App::new()
        .service(whoami)
        .service(org_whoami)
        .app_data(web::Data::new(auth.clone())) // <-- here
})

You can then take User in as an argument, which will look for an access token in the Authorization header.

// User will automatically return a 401 (Unauthorized) if a valid access token wasn't provided
#[get("/whoami")]
async fn whoami(user: User) -> impl Responder {
    HttpResponse::Ok().json(user)
}

You can also check which organizations the user is in, and which roles and permissions they have.

// If the user isn't in the provided organization, a 403 is returned
#[get("/org/{org_name}/whoami")]
async fn whoami(user: User, org_name: web::Path<String>) -> Result<impl Responder, UnauthorizedOrForbiddenError> {
   let org = user.validate_org_membership(RequiredOrg::OrgName(&org_name.into_inner()),
                                          UserRequirementsInOrg::IsRole("Admin"))?;
   Ok(HttpResponse::Ok()
       .body(format!("You are a {} in {}", org.user_role, org.org_name)))
}

You can also get the full auth struct and make API calls with it:

#[post("/magic_link")]
async fn make_req(auth: web::Data<PropelAuth>) -> impl Responder {
    let magic_link = auth.user().create_magic_link(CreateMagicLinkRequest {
        email: "[email protected]".to_string(),
        ..Default::default()
    }).await.expect("Couldn't create magic link");
    HttpResponse::Ok().json(magic_link)
}

Other

After initializing auth, you can verify access tokens by passing in the Authorization header (formatted Bearer TOKEN):

let result = auth.verify().validate_authorization_header(&authorization_header);
match result {
    Ok(user) => { /* valid access token in the header */ }
    Err(_) => { /* invalid access token, typically we return a 401 Unauthorized here */ }
}

You can also check which organizations the user is in, and which roles and permissions they have.

let org = auth.validate_org_membership(
    &authorization_header,
    RequiredOrg::OrgName("acme"),
    UserRequirementsInOrg::IsRole("Admin")
)?;

// Alternatively, if you already have a user from validate_authorization_header
let org = user.validate_org_membership(
    RequiredOrg::OrgName("acme"),
    UserRequirementsInOrg::IsRole("Admin")
)?;

And finally, you can make API calls directly from auth.user() and auth.org()

Where do the access tokens come from?

They come from your frontend. You can read more about integrating your frontend here.

You might also like...
Provides json/csv/protobuf streaming support for axum

axum streams for Rust Library provides HTTP response streaming support for axum web framework: JSON array stream format JSON lines stream format CSV s

Rust Macros to automate the addition of Paths/Schemas to Utoipa crate, simulating Reflection during the compilation phase

utoipa_auto_discovery Rust Macros to automate the addition of Paths/Schemas to Utoipa crate, simulating Reflection during the compilation phase Crate

A WebGPU implementation based on the excellent wgpu crate.

A WebGPU implementation based on the excellent wgpu crate.

A crate built on top of `axum-sessions`, implementing the CSRF Synchronizer Token Pattern

Axum Synchronizer Token Pattern CSRF prevention This crate provides a Cross-Site Request Forgery protection layer and middleware for use with the axum

Download .crate files of all versions of all crates from crates.io

get-all-crates Download .crate files of all versions of all crates from crates.io. Useful for things like noisy-clippy which need to analyze the sourc

Rate Limiting middleware for Tower/Axum/Tonic/Hyper utilizing the governor crate

A Tower service and layer that provides a rate-limiting backend by governor. Based heavily on the work done for actix-governor. Works with Axum, Hyper

A Google-like web search engine that provides the user with the most relevant websites in accordance to his/her query, using crawled and indexed textual data and PageRank.
A Google-like web search engine that provides the user with the most relevant websites in accordance to his/her query, using crawled and indexed textual data and PageRank.

Mini Google Course project for the Architecture of Computer Systems course. Overview: Architecture: We are working on multiple components of the web c

Ergonomic and modular web framework built with Tokio, Tower, and Hyper

axum axum is a web application framework that focuses on ergonomics and modularity. More information about this crate can be found in the crate docume

Proxies all incoming connections to a minecraft server of your choosing, while also logging all ping and login requests to a json file and discord webhook.

minecraft-honeypot Proxies all incoming connections to a minecraft server of your choosing, while also logging all ping and login requests to a json f

Releases(v0.1.0)
Owner
PropelAuth
PropelAuth
Rust Rocket MongoDB token-authorization REST API boilerplate

Rust Rocket MongoDB token-auth REST API boilerplate In this repository, you can find backend Rust rocket mongodb rest-api boilerplate with token autho

null 6 Dec 7, 2022
Oso is an open source policy engine for authorization that’s embedded in your application

Oso What is Oso? Oso is an open source policy engine for authorization that’s embedded in your application. It provides a declarative policy language

oso 2.8k Jan 4, 2023
A simple authentication flow using Rust and Actix-web, with a PostgreSQL database and a sveltekit frontend.

Rust-auth-example This repository aims to represent a simple authentication flow using Rust and Actix-web, with a PostgreSQL database and a sveltekit

Kival Mahadew 4 Feb 19, 2023
A Rust Boilerplate server with GraphQL API, Diesel, PostgreSQL, session authentication and JWT

Canduma rust Graphql A Rust authentication server with GraphQL API, Diesel, PostgreSQL session authentication and JWT This repository contains a Graph

Julien Lenne 738 Dec 28, 2022
JWT Authentication in Rust using Axum Framework

Are you interested in building a secure authentication system for your Rust web application? Look no further than the Axum framework and JSON Web Tokens (JWTs)! Axum is a fast and scalable Rust web framework that provides a reliable and efficient platform for developing microservices and APIs.

CODEVO 16 Jun 11, 2023
🪪 Session-based user authentication for Axum.

axum-login ?? Session-based user authentication for Axum. ?? Overview axum-login is a Tower middleware providing session-based user authentication for

Max Countryman 99 Jan 5, 2023
Axum + JWT authentication Middleware that allows you to start building your application fast

axum_jwt_ware Integration Guide Simple Axum + JWT authentication middleware with implemented Login and refresh token. Goal I aim to simplify the proce

Eze Sunday 3 Dec 2, 2023
Enum path && dir on target URL. Powered by Rust ! 🦀

enum-dir 一款快速枚举目录的小工具,使用 Rust 编写,扫起来真的很快。 用于发现目标站点中可能存在的路径信息,同时支持字典模式和暴力枚举模式。 本工具仅用于学习 Rust 以及 Rust 协程 Tokio 使用,严禁用于非法用途。 如果使用本工具从事违法犯罪活动,造成的任何后果,本人不承

lightless 9 Nov 20, 2022
Perseus is a blazingly fast frontend web development framework built in Rust with support for major rendering strategies

Perseus is a blazingly fast frontend web development framework built in Rust with support for major rendering strategies, reactivity without a virtual DOM, and extreme customizability

arctic_hen7 1.2k Jan 8, 2023
Magnesium-Oxide (MGO) a secure file uploader with support for ShareX.

A blazingly fast, ShareX uploader coded in Rust (using actix web) which utilizes AES-256-GCM-SIV to securely store uploaded content.

Magnesium 26 Nov 25, 2022