Authentication
परिचय
Django Ninja कई tools प्रदान करता है जिनकी मदद से आप authentication और authorization को आसानी से, तेज़ी से और मानक तरीके से संभाल सकते हैं, बिना सभी security specifications को पढ़ने और सीखने की ज़रूरत के।
मुख्य विचार यह है कि जब आप किसी API operation का वर्णन करते हैं, तो आप एक authentication object परिभाषित कर सकते हैं।
from ninja import NinjaAPI
from ninja.security import django_auth
api = NinjaAPI(csrf=True)
@api.get("/pets", auth=django_auth)
def pets(request):
return f"Authenticated user {request.auth}"
इस उदाहरण में, client केवल तभी pets method को कॉल कर पाएगा जब वह Django session authentication (जो डिफ़ॉल्ट रूप से cookie-आधारित है) का उपयोग करे, अन्यथा एक HTTP-401 error लौटाया जाएगा।
यदि आप केवल superusers को authorize करना चाहते हैं, तो आप from ninja.security import django_auth_superuser का उपयोग कर सकते हैं।
Automatic OpenAPI schema
यहाँ एक उदाहरण है जिसमें client को authenticate करने के लिए एक header पास करनी होती है:
Authorization: Bearer supersecret
from ninja.security import HttpBearer
class AuthBearer(HttpBearer):
def authenticate(self, request, token):
if token == "supersecret":
return token
@api.get("/bearer", auth=AuthBearer())
def bearer(request):
return {"token": request.auth}
अब http://localhost:8000/api/docs दस्तावेज़ीकरण पर जाएँ।

अब, जब आप Authorize बटन पर क्लिक करेंगे, तो आपसे अपना authentication token दर्ज करने के लिए कहा जाएगा।

जब आप कोई test कॉल करेंगे, तो हर request authorization header पास करेगी।
Global authentication
यदि आपको अपनी API की सभी methods की सुरक्षा करनी है, तो आप NinjaAPI constructor को auth argument पास कर सकते हैं:
from ninja import NinjaAPI, Form
from ninja.security import HttpBearer
class GlobalAuth(HttpBearer):
def authenticate(self, request, token):
if token == "supersecret":
return token
api = NinjaAPI(auth=GlobalAuth())
# @api.get(...)
# def ...
# @api.post(...)
# def ...
और, यदि आपको कुछ methods को override करने की आवश्यकता है, तो आप इसे auth argument पास करके operation स्तर पर फिर से कर सकते हैं। इस उदाहरण में, /token operation के लिए authentication अक्षम हो जाएगा:
from ninja import NinjaAPI, Form
from ninja.security import HttpBearer
class GlobalAuth(HttpBearer):
def authenticate(self, request, token):
if token == "supersecret":
return token
api = NinjaAPI(auth=GlobalAuth())
# @api.get(...)
# def ...
# @api.post(...)
# def ...
@api.post("/token", auth=None) # < overriding global auth
def get_token(request, username: str = Form(...), password: str = Form(...)):
if username == "admin" and password == "giraffethinnknslong":
return {"token": "supersecret"}
उपलब्ध authentication विकल्प
Custom function
"auth=" argument किसी भी callable को स्वीकार करता है। NinjaAPI तभी authentication पास करेगा जब callable कोई ऐसा मान लौटाए जो truthy हो (boolean True में बदलता हो)। यह return मान request.auth attribute को सौंप दिया जाएगा।
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}"
API keys
कुछ APIs authorization के लिए API keys का उपयोग करती हैं। एक API key एक token है जिसे client API call करते समय खुद की पहचान करने के लिए प्रदान करता है। Key को query string में भेजा जा सकता है:
GET /something?api_key=abcdef12345
या request header के रूप में:
GET /something HTTP/1.1
X-API-Key: abcdef12345
या cookie के रूप में:
GET /something HTTP/1.1
Cookie: X-API-KEY=abcdef12345
Django Ninja इन स्थितियों को संभालने में आपकी मदद के लिए built-in classes के साथ आता है।
Query में
from ninja.security import APIKeyQuery
from someapp.models import Client
class ApiKey(APIKeyQuery):
param_name = "api_key"
def authenticate(self, request, key):
try:
return Client.objects.get(key=key)
except Client.DoesNotExist:
pass
api_key = ApiKey()
@api.get("/apikey", auth=api_key)
def apikey(request):
assert isinstance(request.auth, Client)
return f"Hello {request.auth}"
इस उदाहरण में, हम GET['api_key'] से एक token प्राप्त करते हैं और database में संबंधित Client ढूँढते हैं। Client instance को request.auth attribute के रूप में सेट किया जाएगा।
Note: param_name उस GET parameter का नाम है जिसकी जाँच की जाएगी। यदि सेट नहीं किया गया है, तो डिफ़ॉल्ट "key" का उपयोग किया जाता है।
Header में
from ninja.security import APIKeyHeader
class ApiKey(APIKeyHeader):
param_name = "X-API-Key"
def authenticate(self, request, key):
if key == "supersecret":
return key
header_key = ApiKey()
@api.get("/headerkey", auth=header_key)
def apikey(request):
return f"Token = {request.auth}"
Cookie में
from ninja.security import APIKeyCookie
class CookieKey(APIKeyCookie):
def authenticate(self, request, key):
if key == "supersecret":
return key
cookie_key = CookieKey()
@api.get("/cookiekey", auth=cookie_key)
def apikey(request):
return f"Token = {request.auth}"
HTTP Bearer
from ninja.security import HttpBearer
class AuthBearer(HttpBearer):
def authenticate(self, request, token):
if token == "supersecret":
return token
@api.get("/bearer", auth=AuthBearer())
def bearer(request):
return {"token": request.auth}
HTTP Basic authentication
from ninja.security import HttpBasicAuth
class BasicAuth(HttpBasicAuth):
def authenticate(self, request, username, password):
if username == "admin" and password == "secret":
return username
@api.get("/basic", auth=BasicAuth())
def basic(request):
return {"httpuser": request.auth}
Multiple authenticators
auth argument के साथ आप कई authenticators भी पास कर सकते हैं:
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}"
इस स्थिति में, Django Ninja पहले GET से API key की जाँच करेगा, और यदि वह सेट नहीं है या अमान्य है, तो यह header key की जाँच करेगा।
यदि दोनों अमान्य हैं, तो यह response में एक authentication error उठाएगा।
Router authentication
Router पर auth argument का उपयोग करें ताकि उसमें घोषित सभी operations पर एक authenticator लागू हो:
api.add_router("/events/", events_router, auth=BasicAuth())
या router constructor का उपयोग करते हुए
router = Router(auth=BasicAuth())
Custom exceptions
ऐसा exception उठाना जिसका एक exception handler हो, operation की तरह ही उस handler का response लौटाएगा:
from ninja import NinjaAPI
from ninja.security import HttpBearer
api = NinjaAPI()
class InvalidToken(Exception):
pass
@api.exception_handler(InvalidToken)
def on_invalid_token(request, exc):
return api.create_response(request, {"detail": "Invalid token supplied"}, status=401)
class AuthBearer(HttpBearer):
def authenticate(self, request, token):
if token == "supersecret":
return token
raise InvalidToken
@api.get("/bearer", auth=AuthBearer())
def bearer(request):
return {"token": request.auth}
Async authentication
Django Ninja asynchronous authentication के लिए बुनियादी समर्थन रखता है। हालाँकि डिफ़ॉल्ट authentication classes async-संगत नहीं हैं, फिर भी आप अपना कस्टम async authentication callable परिभाषित कर सकते हैं और उसे auth के साथ पास कर सकते हैं।
async def async_auth(request):
...
@api.get("/pets", auth=async_auth)
def pets(request):
...
अधिक जानकारी के लिए, Error handling देखें।
Success
अगले भाग पर जाएँ Testing
टिप्पणियाँ
पेज व्यूज़:
