[英]Cannot Authenticate Test Requests with Both User Token and API Key in Django Rest Framework
[英]How do I authenticate API requests (by anonymous user) in Django rest framework?
API請求將由匿名用戶發送。 沒有登錄/注冊功能。
我需要驗證API請求,我嘗試過的一種原始方法是在每個請求中發送一個auth密鑰。 這個auth鍵,我作為常量保存在Angular前端。
必須有一個更好,更復雜的方式,請幫助!
Django REST框架主要假設請求是基於用戶進行身份驗證的,但它們確實為身份驗證匿名請求提供支持。 雖然這在很大程度上打破了“身份驗證”意味着“驗證(Django)用戶是真的”的假設,但Django REST框架確實允許它發生,而只是替代AnonymousUser
。
DRF中的身份驗證可以在request.user
定義request.user
(經過身份驗證的用戶)和request.auth
(通常是使用的令牌,如果適用)屬性。 因此,對於您的身份驗證,您將保留已創建的令牌(在模型中或其他位置),並且將驗證這些令牌而不是用戶憑據,並且您最終不會設置用戶。
from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication
from rest_framework import exceptions
class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
auth = authentication.get_authorization_header(request)
if not auth or auth[0].lower() != b'token':
return None
if len(auth) == 1:
msg = _('Invalid token header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid token header. Credentials string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
token = Token.objects.get(token=auth[1])
except Token.DoesNotExist:
raise exceptions.AuthenticationFailed('No such token')
return (AnonymousUser(), token)
此示例假定您具有Token
模型,該模型存儲將要進行身份驗證的令牌。 如果請求已正確驗證,則令牌對象將設置為request.auth
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.