Axum (Rust) Reference - PropelAuth Docs

Axum (Rust) Reference

PropelAuth's Axum library provides all the building blocks you need to add authentication to your Axum projects.

Installation

In your Cargo.toml file, add the following line:

propelauth = { version = "0.9.0", features = ["axum07"] }

# For older versions of Axum, use:
# propelauth = { version = "0.9.0", features = ["axum06"] }

Initialize

There are two options for initializing the library. You can call PropelAuth::fetch_and_init which is an async function that will fetch the metadata needed to verify access tokens. Or, you can call PropelAuth::init and pass in the metadata directly. The later is useful for serverless environments.

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");

Protect API Routes

You'll need to add the PropelAuthLayer to your Router:

let auth_layer = PropelAuthLayer::new(auth);

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

You can then take User in as an argument, which will look for an access token in the Authorization HTTP 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
}

Verifying the access token doesn't require an external request.

Authorization / Organizations

You can also verify which organizations the user is in, and which roles and permissions they have, with the validate_org_membership function on the user object.

Check Org Membership

Verify that the request was made by a valid user and that the user is a member of the specified organization. This can be done using the User object.

// 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::OrgId(&org_id),
                                           UserRequirementsInOrg::None)?;
    Ok(format!("You are in {}", org.org_name))
}

Check Org Membership and Role

Similar to checking org membership, but will also verify that the user has a specific Role in the organization. This can be done using either the User or OrgMemberInfo objects.

// Assuming a Role structure of Owner => Admin => Member
async fn org_whoami(user: User,
                    Path(org_name): Path<String>) -> Result<String, UnauthorizedOrForbiddenError> {
    let org = user.validate_org_membership(RequiredOrg::OrgId(&org_id),
                                           UserRequirementsInOrg::IsRole("Admin"))?;
    Ok(format!("You are a {} in {}", org.user_role, org.org_name))
}

Check Org Membership and Permission

Similar to checking org membership, but will also verify that the user has the specified permission in the organization. This can be done using either the User or OrgMemberInfo objects.

async fn org_whoami(user: User,
                    Path(org_name): Path<String>) -> Result<String, UnauthorizedOrForbiddenError> {
    let org = user.validate_org_membership(RequiredOrg::OrgId(&org_id),
                                           UserRequirementsInOrg::HasPermission("can_view_billing"))?;
    Ok(format!("You can view billing in org {}", org.org_name))
}

User

The User object contains information about the user that made the request.

OrgMemberInfo

The OrgMemberInfo object contains information about the user's membership in an organization.

Calling Backend APIs

You can also use the library to call the PropelAuth APIs directly, allowing you to fetch users, create orgs, and a lot more.

// 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: "user@customer.com".to_string(),
        ..Default::default()
    }).await.expect("Couldn't create magic link");
    magic_link.url
}

See the API Reference for more information.