赞
踩
django_auth其实就是SessionAuth类鉴权方式。
使用Django自带的auth模块,通过/login实现登录,然后可以访问/api_withdjango_auth。
通过/logout可以退出登录。
- 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}"}
-
- __all__ = [
- "APIKeyCookie",
- "APIKeyHeader",
- "APIKeyQuery",
- "HttpBasicAuth",
- "HttpBearer",
- "SessionAuth",
- "SessionAuthSuperUser",
- "django_auth",
- ]
"auth="参数接收一个Callable对象。如果这个对象的返回结果可以转换成布尔类型的True值时,NinjaAPI即可通过鉴权。同时这个值也会被赋给request.auth。
- 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}"
逐个鉴权器进行鉴权,有一个通过即可通过。
- 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}"
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。