【Django-ninja】使用Django ninja 进行auth鉴权

1. 使用django_auth

django_auth其实就是SessionAuth类鉴权方式。

使用Django自带的auth模块,通过/login实现登录,然后可以访问/api_withdjango_auth。

通过/logout可以退出登录。

python 复制代码
from django.contrib import auth


class LoginSchema(Schema):
    user:str
    password: str


@demo_api.get('/login')
def login(request, login_in: LoginSchema=Query(...)):
    user = auth.authenticate(request, username=login_in.user, password=login_in.password)
    if user:
        auth.login(request, user)
        return {"message": str(request.session), 'request': str(request)}
    else:
        return {"message": "fail"}


@demo_api.get('/logout')
def logout(request):
    auth.logout(request)
    return {"message": "logout", "session": str(request.session), 'request': str(request)}


@demo_api.get("/django_auth", auth=django_auth)
def api_with_django_auth(request):
    return {"data": request.session[auth.HASH_SESSION_KEY], "auth": f"{request.auth}"}

2.其他所有内置的鉴权方式

python 复制代码
__all__ = [
    "APIKeyCookie",
    "APIKeyHeader",
    "APIKeyQuery",
    "HttpBasicAuth",
    "HttpBearer",
    "SessionAuth",
    "SessionAuthSuperUser",
    "django_auth",
]

3. 自定义鉴权方式

"auth="参数接收一个Callable对象。如果这个对象的返回结果可以转换成布尔类型的True值时,NinjaAPI即可通过鉴权。同时这个值也会被赋给request.auth。

python 复制代码
def ip_whitelist(request):
    if request.META["REMOTE_ADDR"] == "8.8.8.8":
        return "8.8.8.8"


@api.get("/ipwhitelist", auth=ip_whitelist)
def ipwhitelist(request):
    return f"Authenticated client, IP = {request.auth}"

4.多个鉴权器

逐个鉴权器进行鉴权,有一个通过即可通过。

python 复制代码
from ninja.security import APIKeyQuery, APIKeyHeader


class AuthCheck:
    def authenticate(self, request, key):
        if key == "supersecret":
            return key


class QueryKey(AuthCheck, APIKeyQuery):
    pass


class HeaderKey(AuthCheck, APIKeyHeader):
    pass


@api.get("/multiple", auth=[QueryKey(), HeaderKey()])
def multiple(request):
    return f"Token = {request.auth}"
相关推荐
风之所往_1 小时前
Python 3.0 新特性全面总结
python
2401_882273721 小时前
如何在 CSS 中正确加载本地 JPG 背景图片
jvm·数据库·python
Lucas_coding1 小时前
【Claude Code Router】 Claude Code 兼容 OpenAI 格式 API, Claude code 接入本地部署模型
人工智能·python
测试员周周1 小时前
【AI测试系统】第5篇:从 Archon 看 AI 工程化落地:为什么"确定性编排+AI 弹性智能"是终局?
人工智能·python·测试
大飞记Python2 小时前
【2026更新】Python基础学习指南(AI版)——04数据类型
开发语言·人工智能·python
Hello eveybody3 小时前
介绍一下背包DP(Python)
开发语言·python·动态规划·dp·背包dp
2301_795099744 小时前
让 CSS Grid 自适应容器尺寸的动态布局方案
jvm·数据库·python
呆萌的代Ma4 小时前
python读取并加载.env的配置文件
python
Muyuan19984 小时前
27.RAG 系统中的上下文充分性判断:从 Chunk 数量、FAISS 距离到 LLM Relevance Gate
python·django·pdf·fastapi·faiss
U盘失踪了4 小时前
python curl转python脚本
开发语言·chrome·python