Skip to main content

Python permission authentication framework inspired by sa-token, with FastAPI integration

Project description

liteauth

liteauth

Python 权限认证框架,源自 sa-token 的设计思想。

Python License


特性

  • 登录/注销 — 单端/多端登录、同端互斥
  • 踢人下线 — 按用户 ID 或 Token 精确踢出
  • 权限/角色校验 — 通配符支持(art.*art.add
  • Session 管理 — Account-Session(跨设备)/ Token-Session(单设备)
  • 账号封禁 — 分类封禁 + 阶梯封禁
  • 多账号体系AuthLogic("user") / AuthLogic("admin") 独立隔离
  • SSO 单点登录 — 三种模式
  • OAuth2.0 — 授权服务器(Authorization Code / Implicit / Client Credentials)
  • JWT 模式 — 标准 / 无状态 / Mixin 三种模式
  • FastAPI — 独立依赖函数、装饰器、中间件
  • 可插拔存储 — 内存 / 磁盘(SQLite) / Redis

安装

pip install liteauth

# 可选依赖
pip install liteauth[fastapi]   # FastAPI 集成
pip install liteauth[redis]     # Redis 存储
pip install liteauth[jwt]       # JWT 模式
pip install liteauth[crypto]    # AES 加密
pip install liteauth[all]       # 全部

快速开始

核心 API

from liteauth import AuthLogic, PermissionInterface, AuthManager

class MyPermission(PermissionInterface):
    async def get_permission_list(self, login_id, login_type):
        return {"admin": ["*"]}.get(login_id, ["user:view"])
    async def get_role_list(self, login_id, login_type):
        return {"admin": ["admin"]}.get(login_id, ["user"])

# 统一初始化(推荐在应用启动时调用一次)
AuthManager.init(
    permission_interface=MyPermission(),
)

auth = AuthLogic()
await auth.login("admin")

FastAPI

from fastapi import FastAPI, Depends
from liteauth import AuthLogic, AuthManager
from liteauth.integration.fastapi import login_required, require_permission, register_exception_handlers

app = FastAPI()

AuthManager.init(
    permission_interface=MyPermission(),
)

auth = AuthLogic()
AuthManager.register_auth(auth)
register_exception_handlers(app)

@app.post("/login")
async def login(username: str):
    return await auth.login(username)

@app.get("/users/me")
async def me(user_id: str = Depends(login_required())):
    return {"user_id": user_id}

@app.get("/admin")
async def admin(_: None = Depends(require_permission("admin:panel"))):
    return {"msg": "welcome"}

装饰器

from liteauth.integration.fastapi.decorator import login_required, require_permission, require_role, ignore_auth

@router.get("/users")
@login_required
async def users(): ...

@router.get("/admin")
@require_permission("admin:panel")
async def admin(): ...

@router.get("/public")
@ignore_auth
async def public(): ...

JWT 无状态模式

from liteauth import JwtStatelessLogic, AuthConfig

auth = JwtStatelessLogic(config=AuthConfig(
    jwt_secret="my-secret-key",
    jwt_access_token_timeout=3600,
))

result = await auth.login("user123")
# → TokenResponse(access_token="eyJ...", refresh_token="eyJ...")

await auth.check_login()   # 解码 JWT,不查数据库
new = await auth.refresh(result.refresh_token)  # 刷新 Token

四种认证模式

JWT Simple

from liteauth import JwtSimpleLogic, AuthConfig

auth = JwtSimpleLogic(config=AuthConfig(jwt_secret="my-key"))
result = await auth.login("user123")     # token 是 JWT
await auth.check_login()                  # 走 DAO 查询
await auth.kickout("user123")             # 完整支持

对比

标准 JWT Simple JWT 无状态 JWT Mixin
Token 格式 UUID JWT JWT JWT
Token 校验 DAO DAO JWT 解码 JWT 解码
踢人下线
Token-Session
双 Token
get_extra()

异常处理

一行注册,自动转换异常为 JSON 响应:

from liteauth.integration.fastapi import register_exception_handlers
register_exception_handlers(app)
异常 HTTP 响应示例
NotLoginException 401 {"detail":"已被踢下线","code":"NOT_LOGIN","scene":"-5"}
NotPermissionException 403 {"detail":"无此权限","code":"PERMISSION_DENIED","permission":"admin:panel"}
NotRoleException 403 {"detail":"无此角色","code":"ROLE_DENIED","role":"admin"}
DisableServiceException 403 {"detail":"账号已被封禁","code":"DISABLE"}

存储后端

# 内存(默认,开发/测试)
from liteauth import MemoryDao
dao = MemoryDao(size=100_000)

# 磁盘持久化(SQLite,单机生产)
from liteauth.dao.disk import DiskDao
dao = DiskDao(directory="./auth_cache")

# Redis(分布式生产)
from liteauth import RedisDao
dao = RedisDao.from_url("redis://localhost:6379/0")

# 使用
auth = AuthLogic(dao=dao)

多账号体系

user_auth = AuthLogic(login_type="user")
admin_auth = AuthLogic(login_type="admin")

AuthManager.register_auth(user_auth)
AuthManager.register_auth(admin_auth)

# FastAPI
@app.get("/admin")
async def admin(_: None = Depends(require_permission("admin:panel", login_type="admin"))):
    ...

高级特性

SSO 单点登录

from liteauth.sso import SsoConfig, SsoRouter, SsoClient

router = SsoRouter(SsoConfig(server_url="http://auth.example.com"))
app.include_router(router.get_router(), prefix="/sso")

client = SsoClient(auth, config=sso_config)

OAuth2.0

from liteauth.oauth2 import OAuth2Config, OAuth2Client, OAuth2Router

# FastAPI 路由
router = OAuth2Router(OAuth2Config(server_url="http://localhost:8000"))
app.include_router(router.get_router(), prefix="/oauth2")

# Flask 用户可直接使用 OAuth2Template + 自定义路由
template = OAuth2Template(config)
await template.authorize(client_id="app1", response_type="code", user_id="123")

临时 Token

from liteauth import TempTokenUtil

token = TempTokenUtil.create_token("user@example.com", timeout=300, secret="key")
value = TempTokenUtil.parse_token(token, secret="key")  # → "user@example.com"

二级认证

await auth.open_safe(service="payment", timeout=120)   # 开启
await auth.check_safe(service="payment")                 # 校验
await auth.close_safe(service="payment")                 # 关闭

依赖

模块 依赖
核心 pydantic>=2.0, cashews>=7.5
FastAPI fastapi>=0.139
Redis redis>=8.0
JWT pyjwt>=2.13
Crypto cryptography>=49.0

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

liteauth-0.2.9.tar.gz (6.8 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

liteauth-0.2.9-py3-none-any.whl (90.5 kB view details)

Uploaded Python 3

File details

Details for the file liteauth-0.2.9.tar.gz.

File metadata

  • Download URL: liteauth-0.2.9.tar.gz
  • Upload date:
  • Size: 6.8 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for liteauth-0.2.9.tar.gz
Algorithm Hash digest
SHA256 3043e38b5ca3bffa3a04ffb3b9dcf4a6eec381e6cc63823132b8f42ad0121b9b
MD5 4ec6d0e0a0ec40b30168239e37acb864
BLAKE2b-256 053432eab51406c5a2e69afe464b59fdba73b1c62384e28ef49487f4deec0380

See more details on using hashes here.

File details

Details for the file liteauth-0.2.9-py3-none-any.whl.

File metadata

  • Download URL: liteauth-0.2.9-py3-none-any.whl
  • Upload date:
  • Size: 90.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for liteauth-0.2.9-py3-none-any.whl
Algorithm Hash digest
SHA256 423c1d7cd7c7d453e075b817b8b0b5fc67a8d07eb8584f3ef5cda4f0e032414b
MD5 7b3e55dbea81c85c7d311d4694deab86
BLAKE2b-256 56d8b5e7a2f271cd1508b5f8725736de60ca6d844a2919ade82d27635d566797

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page