Djoser के साथ Django Ninja Token Authentication
Source URL: https://stackoverflow.com/questions/70716976/django-ninja-token-authentication-with-djoser
चीनी content: यह प्रश्न शोध प्रयास दर्शाता है; यह उपयोगी और स्पष्ट है
2
इस प्रश्न को सहेजें।
इस post पर गतिविधि दिखाएं।
मैंने Django Ninja framework का उपयोग करके CRUD implement किया है, लेकिन अब मैं अपनी application में authenticate करना चाहता हूँ। मैंने Djoser install और configure कर लिया है, इसलिए अब मैं tokens generate कर सकता हूँ, लेकिन मुझे नहीं पता कि अपने CRUD में उन्हें कैसे सत्यापित करूँ
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}
मुझे "AuthBearer" function में token की जाँच करने में सक्षम होना चाहिए, लेकिन मुझे नहीं पता कि कैसे
मेरी repo (link)
इस प्रश्न का एक link share करें
Copy linkCC BY-SA 4.0
Follow
इस प्रश्न को follow करें ताकि notifications प्राप्त हो सकें
12.3k2222 gold badges6868 silver badges103103 bronze badges
Asked Jan 14, 2022 at 21:59
ArsalanArsalan
7722 silver badges99 bronze badges
1 उत्तर 1
Sort by: Reset to default
Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
यह उत्तर उपयोगी है
6
उत्तर को सहेजें।
इस post पर गतिविधि दिखाएं।
तो मूल रूप से आपको Ninja की HttpBearer class को extend करना होगा और authenticate method implement करना होगा, जो arguments के रूप में request और token स्वीकार करेगा। यदि user authenticated नहीं है तो यह method None return करेगा, या एक string return करेगा जो user के authenticated होने पर request.auth में populate होगी। आमतौर पर, यह string username होगी, ताकि आप इसे सभी endpoints में उपयोग कर सकें। कुछ इस तरह (मैं token decode करने के लिए PyJWT का उपयोग कर रहा हूँ):
import jwt
from ninja.security import HttpBearer
class AuthBearer(HttpBearer):
def authenticate(self, request, token):
try:
#JWT secret key is set up in settings.py
JWT_SIGNING_KEY = getattr(settings, "JWT_SIGNING_KEY", None)
payload = jwt.decode(token, JWT_SIGNING_KEY, algorithms=["HS256"])
username: str = payload.get("sub")
if username is None:
return None
except jwt.PyJWTError as e:
return None
return username
इस उत्तर का एक link share करें
Copy linkCC BY-SA 4.0
Follow
इस उत्तर को follow करें ताकि notifications प्राप्त हो सकें
Answered Jan 15, 2022 at 11:30 AM
abolfazlmalekahmadiabolfazlmalekahmadi
26822 silver badges1717 bronze badges
1
- इस code example के लिए धन्यवाद! आप encoded token कैसे generate करते हैं? क्या आप इन tokens को storage में रखते हैं?
Commented Jul 18, 2023 at 9:29
@media (prefers-color-scheme: dark) { body { color: #fff !important; background-color: #272727 !important; } } body { overflow-y: hidden; }
पेज व्यूज़:

