【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 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪5 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽5 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战6 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋11 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama