【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}"
相关推荐
RSTJ_162524 分钟前
PYTHON+AI LLM DAY THREETY-SEVEN
开发语言·人工智能·python
郝学胜-神的一滴28 分钟前
深度学习优化核心:梯度下降与网络训练全解析
数据结构·人工智能·python·深度学习·算法·机器学习
Mr数据杨34 分钟前
【Codex】用Tauri用户配置打通桌面端个性化设置
django·codex·项目开发
Aision_37 分钟前
Agent 为什么需要 Checkpoint?
人工智能·python·gpt·langchain·prompt·aigc·agi
清水白石00842 分钟前
《Python性能深潜:从对象分配开销到“小对象风暴”的破解之道(含实战与最佳实践)》
开发语言·python
Land03292 小时前
RPA工具选型技术指南:架构差异与实测数据
python·自动化·rpa
kafei_*2 小时前
VScode 添加 UV虚拟环境方法
vscode·python·uv
洛_尘3 小时前
Python 5:使用库
java·前端·python
m0_596749093 小时前
如何防止SQL拼接漏洞_使用PDO对象实现安全的SQL交互
jvm·数据库·python
Mr数据杨3 小时前
【Codex】用整合教案模块串联PPT文案与课堂教学方案
django·powerpoint·codex·项目开发