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.8.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.8-py3-none-any.whl (90.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: liteauth-0.2.8.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.8.tar.gz
Algorithm Hash digest
SHA256 0ad19b2b1eb2c73f4c126665966351cc9081248ab4e87120e29035e0c6ea2a1e
MD5 85a2cf2873895a1489d2f345dd4bdb75
BLAKE2b-256 6eed4c2fc3d6a3173d08af31d30860d9f07a4cb3ae0ef193ec7aa60fcf987a59

See more details on using hashes here.

File details

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

File metadata

  • Download URL: liteauth-0.2.8-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.8-py3-none-any.whl
Algorithm Hash digest
SHA256 1fc09cb25cc46368066de3963a74bd58ff1b92d45dab449c3ca195f5a03724f0
MD5 e085daebf3e31b7851617b3bb7b24ca1
BLAKE2b-256 dd5e5b4720b543781e64d819437287b6815c03d7a0ddd334cab0acdb92d394b2

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