【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}"
相关推荐
冷雨夜中漫步3 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴3 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再3 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
喵手5 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934735 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy5 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
肖永威7 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ7 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
枷锁—sha7 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
abluckyboy7 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法