ali*_*sav 3 django django-rest-framework
API请求将由匿名用户发送.没有登录/注册功能.
我需要验证API请求,我尝试过的一种原始方法是在每个请求中发送一个auth密钥.这个auth键,我作为常量保存在Angular前端.
必须有一个更好,更复杂的方式,请帮助!
Kev*_*own 12
Django REST框架主要假设请求是基于用户进行身份验证的,但它们确实为身份验证匿名请求提供支持.虽然这很大程度上打破了"身份验证"意味着"验证(Django)用户是真实的"这一假设,但Django REST框架确实允许它发生,而只是替代它AnonymousUser.
DRF中的身份验证可以定义请求上的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)
Run Code Online (Sandbox Code Playgroud)
此示例假定您具有Token存储将要进行身份验证的令牌的模型.request.auth如果请求已正确验证,则令牌对象将设置为.
| 归档时间: |
|
| 查看次数: |
3929 次 |
| 最近记录: |