【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}"
相关推荐
YJlio14 分钟前
7.4.5 Windows 11 企业网络连接与网络重置实战:远程访问、本地策略与故障恢复
前端·chrome·windows·python·edge·机器人·django
深耕AI18 分钟前
【VS Code避坑指南】点击Python图标提示“没有Python环境”,选择安装uv后这堆输出到底是什么意思?
开发语言·python·uv
第一程序员18 分钟前
Rust生命周期管理实战指南:从困惑到掌握
python·github
程序员威哥22 分钟前
实战!Python爬京东商品评论:从采集到情感分析+词云可视化,新手30分钟跑通
开发语言·爬虫·python·scrapy
风噪39 分钟前
centos7 python3.13全套安装(可用于离线复制)
python
小陈的进阶之路1 小时前
Python系列课(5)——数据容器
windows·python
知识领航员1 小时前
2026年推荐6个AI音乐工具
java·人工智能·python·eclipse·django·php·pygame
PieroPc1 小时前
证件裁切拼版工具
python
2401_833033622 小时前
golang如何实现MQTT主题通配符路由_golang MQTT主题通配符路由实现策略
jvm·数据库·python
AI精钢2 小时前
修复 AI Gateway 图片 MIME 类型错误:用魔数检测替代扩展名猜测
网络·人工智能·python·gateway·aigc