#session #axum #sqlx #user-management #tower

axum_session_auth

提供用户认证和权限令牌检查的库。它需要Axum_Session库。

3个版本 (重大更新)

0.14.0 2024年4月12日
0.13.0 2024年3月11日
0.12.1 2024年2月14日
0.11.0 2023年12月21日
0.1.1 2023年3月31日

#329数据库接口

Download history 158/week @ 2024-04-28 92/week @ 2024-05-05 88/week @ 2024-05-12 99/week @ 2024-05-19 147/week @ 2024-05-26 190/week @ 2024-06-02 172/week @ 2024-06-09 168/week @ 2024-06-16 93/week @ 2024-06-23 93/week @ 2024-06-30 106/week @ 2024-07-07 198/week @ 2024-07-14 191/week @ 2024-07-21 251/week @ 2024-07-28 191/week @ 2024-08-04 164/week @ 2024-08-11

每月810次下载
audiobookroom 中使用

MIT/Apache

44KB
647

Axum Session Auth

提供用户认证和权限令牌检查的库。它需要Axum_Session库。此库将帮助确保用户ID或授权不会存储在客户端,而是在服务器端。授权通过客户端存储在客户端的Server端会话ID进行链接。之前被称为Axum Sessions Auth

https://crates.io/crates/axum_session_auth Docs

  • 包装 axum_session 用于数据管理服务器端。
  • 右键管理API
  • 用户数据加载时自动加载。
  • 避免在不需要时重复数据库调用。

帮助

如果你需要帮助或有建议,请访问我们的 Discord群组

安装

axum_session 运行时和 ['axum_session']

# Cargo.toml
[dependencies]
# Postgres + rustls
axum_session_auth = { version = "0.14.0" }
axum_session_sqlx = { version = "0.1.0" }

Cargo功能标志

功能 描述
高级 启用函数以提供更多对会话的直接控制。
rest_mode 禁用Cookie处理,仅使用Header only用法进行Rest API请求和响应。
key-store 启用可选的关键存储。这将增加基于Fastbloom设置的RAM使用。
数据库Crate 持久化 描述
axum_session_sqlx Sqlx会话存储
axum_session_surreal Surreal会话存储
axum_session_mongo Mongo会话存储
axum_session_redispool RedisPool会话存储

示例

use sqlx::{PgPool, ConnectOptions, postgres::{PgPoolOptions, PgConnectOptions}};
use std::net::SocketAddr;
use axum_session::{Session, SessionConfig, SessionLayer, DatabasePool};
use axum_session_auth::{AuthSession, AuthSessionLayer, Authentication, AuthConfig, HasPermission};
use axum_session_sqlx::SessionPgPool;
use axum::{
    Router,
    routing::get,
};

#[tokio::main]
async fn main() {
    # async {
        let poll = connect_to_database().await.unwrap();

        let session_config = SessionConfig::default()
            .with_database("test")
            .with_table_name("test_table");
        let auth_config = AuthConfig::<i64>::default().with_anonymous_user_id(Some(1));
        let session_store = SessionStore::<SessionPgPool>::new(Some(poll.clone().into()), session_config);

        // Build our application with some routes
        let app = Router::new()
            .route("/greet/:name", get(greet))
            .layer(SessionLayer::new(session_store))
            .layer(AuthSessionLayer::<User, i64, SessionPgPool, PgPool>::new(Some(poll)).with_config(auth_config));

        // Run it
        let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
        tracing::debug!("listening on {}", addr);
        axum::Server::bind(&addr)
            .serve(app.into_make_service())
            .await
            .unwrap();
        # };
}

// We can obtain the method to compare with the methods we allow, which is useful if this supports multiple methods.
// When called, auth is loaded in the background for you.
async fn greet(method: Method, auth: AuthSession<User, i64, SessionPgPool, PgPool>) -> &'static str {
    let mut count: usize = auth.session.get("count").unwrap_or(0);

    // We will get the user if not, then a guest which should be our default.
    let current_user = auth.current_user.clone().unwrap_or_default();
    count += 1;

    // Session is also included with Auth so there's no need to require it in the function arguments if you're using AuthSession.
    auth.session.set("count", count);

    // If, for some reason, you needed to update your user's permissions
    // or data that is cached, then you will want to clear the user cache if it is enabled.
    // The user Cache is enabled by default. To clear, simply use:
    auth.cache_clear_user(1).await;
    // To clear all cached user data for a large update:
    auth.cache_clear_all().await;

    // This is our Auth Permission Builder and Rights Checker. We build it with methods to check for permissions.
    // In this case, if the page is loaded using Method::Get, it will proceed successfully. However, if Method::Post is used, it will fail with the "no Permissions!" error.
    // The boolean value "false" is used to determine whether authentication is required. When set to true, it triggers the function is_authenticated().
    if !Auth::<User, i64, PgPool>::build([Method::Get], false)
        // We prepare which rights we accept or deny from guests or other users.
        .requires(Rights::none([
            Rights::permission("Token::UseAdmin"),
            Rights::permission("Token::ModifyPerms"),
        ]))
        // We then validate the current user and method. We also pass our database along for database permissions checking if required; otherwise, None.
        .validate(&current_user, &method, None)
        .await
    {
        // We return a "No Permissions" message if validation fails for any reason.
        return format!("No Permissions! for {}", current_user.username)[];
    }

    // Since we had the is_authenticated set to false Above we will instead use it to log in our Guest user.
    if !auth.is_authenticated() {
        // Set the user ID of the User to the Session so it can be Auto Loaded the next load or redirect
        auth.login_user(2);
        // Set the session to be long term. Good for Remember me type instances.
        auth.remember_user(true);
        // We don't currently know the username until the next page access.
        // so Normally we would Redirect here after login if we did indeed log in.
        // But in this case we will just let the user know to reload the page for the example.
        "You have Logged in! Please Refresh the page to display the username and counter."
    } else {

        // Upon page reload, if the user possesses all necessary permissions, the method is accurate, and they are logged in,
        // their username and a count that increments with each page refresh will be displayed.
        format!("{}-{}", current_user.username, count)[..]
    };
}

#[derive(Clone, Debug)]
pub struct User {
    pub id: i32,
    pub anonymous: bool,
    pub username: String,
}

// This is only used if you want to use Token based Authentication checks
#[async_trait]
impl HasPermission<PgPool> for User {
    async fn has(&self, perm: &String, _pool: &Option<&PgPool>) -> bool {
        match &perm[..] {
            "Token::UseAdmin" => true,
            "Token::ModifyUser" => true,
            _ => false,
        }
    }
}

#[async_trait]
impl Authentication<User, i64, PgPool> for User {
    // This is run when the user has logged in and has not yet been Cached in the system.
    // Once ran it will load and cache the user.
    async fn load_user(userid: i64, _pool: Option<&PgPool>) -> Result<User> {
        Ok(User {
            id: userid,
            anonymous: true,
            username: "Guest".to_string(),
        })
    }

    // This function is used internally to determine if they are logged in or not.
    fn is_authenticated(&self) -> bool {
        !self.anonymous
    }

    fn is_active(&self) -> bool {
        !self.anonymous
    }

    fn is_anonymous(&self) -> bool {
        self.anonymous
    }
}

async fn connect_to_database() -> anyhow::Result<sqlx::Pool<sqlx::Postgres>> {
    // ...
    # unimplemented!()
}

依赖关系

~10–19MB
~241K SLoC