• Stars
    star
    550
  • Rank 80,567 (Top 2 %)
  • Language
    Rust
  • License
    MIT License
  • Created about 2 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸͺͺ User identification, authentication, and authorization for Axum.

axum-login

πŸͺͺ Session-based user authentication for Axum.

🎨 Overview

axum-login is a Tower middleware providing session-based user authentication for axum applications.

  • Decouples user storage from authentication
  • Supports arbitrary user types and arbitrary storage backends
  • Provides methods for: logging in, logging out, and accessing current user
  • Optional role-based access controls via an arbitrary role type
  • Wraps axum-sessions to provide flexible sessions
  • Leverages tower_http::auth::RequireAuthorizationLayer to protect routes

Note axum-login implements a fundamental pattern for user authentication, however some features may be missing. Folks are encouraged to make suggestions for extensions to the library.

πŸ“¦ Install

To use the crate in your project, add the following to your Cargo.toml file:

[dependencies]
axum-login = "0.5.0"

🀸 Usage

axum applications can use the middleware via the auth layer.

axum Example

use axum::{response::IntoResponse, routing::get, Extension, Router};
use axum_login::{
    axum_sessions::{async_session::MemoryStore, SessionLayer},
    secrecy::SecretVec,
    AuthLayer, AuthUser, RequireAuthorizationLayer, SqliteStore,
};
use rand::Rng;
use sqlx::sqlite::SqlitePoolOptions;

#[derive(Debug, Default, Clone, sqlx::FromRow)]
struct User {
    id: i64,
    password_hash: String,
    name: String,
}

impl AuthUser<i64> for User {
    fn get_id(&self) -> i64 {
        self.id
    }

    fn get_password_hash(&self) -> SecretVec<u8> {
        SecretVec::new(self.password_hash.clone().into())
    }
}

type AuthContext = axum_login::extractors::AuthContext<i64, User, SqliteStore<User>>;

#[tokio::main]
async fn main() {
    let secret = rand::thread_rng().gen::<[u8; 64]>();

    let session_store = MemoryStore::new();
    let session_layer = SessionLayer::new(session_store, &secret).with_secure(false);

    let pool = SqlitePoolOptions::new()
        .connect("sqlite/user_store.db")
        .await
        .unwrap();

    let user_store = SqliteStore::<User>::new(pool);
    let auth_layer = AuthLayer::new(user_store, &secret);

    async fn login_handler(mut auth: AuthContext) {
        let pool = SqlitePoolOptions::new()
            .connect("sqlite/user_store.db")
            .await
            .unwrap();
        let mut conn = pool.acquire().await.unwrap();
        let user: User = sqlx::query_as("select * from users where id = 1")
            .fetch_one(&mut conn)
            .await
            .unwrap();
        auth.login(&user).await.unwrap();
    }

    async fn logout_handler(mut auth: AuthContext) {
        dbg!("Logging out user: {}", &auth.current_user);
        auth.logout().await;
    }

    async fn protected_handler(Extension(user): Extension<User>) -> impl IntoResponse {
        format!("Logged in as: {}", user.name)
    }

    let app = Router::new()
        .route("/protected", get(protected_handler))
        .route_layer(RequireAuthorizationLayer::<i64, User>::login())
        .route("/login", get(login_handler))
        .route("/logout", get(logout_handler))
        .layer(auth_layer)
        .layer(session_layer);

    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

You can find this example as well as other example projects in the example directory.

See the crate documentation for more usage information.

More Repositories

1

flask-login

Flask user session management.
Python
3,532
star
2

flask-bcrypt

Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.
Python
323
star
3

tower-sessions

πŸ₯  Sessions as a `tower` and `axum` middleware.
Rust
214
star
4

flask-uploads

File uploads for Flask.
Python
208
star
5

flask-seasurf

SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).
Python
190
star
6

logmon

Realtime log reader in Flask
Python
176
star
7

flake

Decentralized, k-ordered unique IDs in Clojure
Clojure
142
star
8

atomos

Atomic primitives for Python.
Python
119
star
9

warc-parquet

πŸ—„οΈ A simple CLI for converting WARC to Parquet.
Rust
103
star
10

axum-sessions

πŸ₯  Cookie-based sessions for Axum via async-session.
Rust
74
star
11

aquamarine

A demo of zero-downtime deploys with Docker Compose and Traefik
Shell
53
star
12

irctk

A simple framework for writing IRC applications
Python
44
star
13

quanta

Distributed CRDT of sparse integer vectors.
Clojure
33
star
14

forma

🐚 An opinionated SQL formatter.
Rust
27
star
15

axum-messages

πŸ›ŽοΈ One-time notification messages for Axum.
Rust
26
star
16

tower-sessions-stores

πŸšƒ Previously bundled session stores for `tower-sessions`.
Rust
23
star
17

hyperlight

A performance-focused HTTP reverse proxy
Clojure
19
star
18

flask-themes

Flask Themes
Python
19
star
19

cryptotrade

A simple Python API wrapper for Bitcoin trading platforms such as MtGox and TradeHill
Python
14
star
20

flog

A blog written with Flask
Python
9
star
21

flask-wepay

A Flask wrapper for WePay's Python API
Python
8
star
22

blizzard

HTTP unique ID generation service
Clojure
8
star
23

st

Fast and simple statistics on the command line.
Rust
6
star
24

markov-domains

Finds available domains using Markov chains.
Clojure
6
star
25

nautilus

User authentication and management service
Clojure
5
star
26

yelp-api

A wrapper for Yelp's public API
PHP
4
star
27

affinis

An IRC library for Clojure.
Clojure
4
star
28

wtforms

Python
4
star
29

rauth

A Python library for OAuth 1.0/a, 2.0, and Ofly
Python
4
star
30

simpleirc

An IRC connection layer written in Python.
Python
4
star
31

headers-accept

🀝 The missing `Accept` implementation for `headers::Header`.
Rust
4
star
32

pyxine-branch

Branch of the Python extension for xine
Python
3
star
33

fluyt

ClojureScript HTTP requests
Clojure
3
star
34

cozy

A modern Node API template for the weary traveller
JavaScript
3
star
35

ewt

EDN Web Tokens
Clojure
3
star
36

dotfiles

Development environment configuration files.
Shell
3
star
37

flask-simpleoauth

A dead simple OAuth 1.0a provider in Flask
Python
3
star
38

simpleoauth

Simple, correct OAuth 1.0 and 2.0 signing methods.
Python
2
star
39

kaa

Kaa is the resident IRC bot on VoxInfinitus, written with IrcTK
Python
2
star
40

voxinfinitus

Basic Django apps providing CMS and blog functionality for Voxi
Python
2
star
41

mage

A Clojure-like Lisp.
Python
2
star
42

tasker

simple task manager
Python
2
star
43

ChatOnMacWebAPI-Swift

Swift
2
star
44

chatter

Chatter is a quick and dirty realtime chat application written in Flask
Python
2
star
45

bitpit-https-bridge

A simple Flask app to bridge the unsecured service with a secured page
Python
1
star
46

conceptis.org

My personal site and blog
Python
1
star
47

primes

A simple Clojure program for generating a multiplication table of primes
Clojure
1
star
48

konvej

Httpbin in Clojure.
Clojure
1
star
49

atrium

HTTP Authentication Service
1
star
50

clasp

A dead simple routing DSL for Clojure's ring.
Clojure
1
star
51

celeb

Incomplete Flask gallery project, now abandoned
Python
1
star
52

accord

A simple OAuth 1.0/a, 2.0 consumer client for Clojure.
Clojure
1
star
53

locksmithing

Lock-free, concurrent data structure experiments.
Clojure
1
star