在我的django应用中,我使用rest_framework创建了一个自定义的认证类:
from business.models import BusinessToken
from rest_framework.authtoken.models import Token
from rest_framework import authentication, exceptions
class AuthenticationMixin(authentication.BaseAuthentication):
def authenticate(self, request):
raw_token = request.META.get('HTTP_AUTHORIZATION')
if not raw_token:
return None
token_key = raw_token.replace("Token ", "")
user_token = Token.objects.filter(key=token_key).first()
if user_token is not None:
user = user_token.user
request.user = user
return user, None
business_token = BusinessToken.objects.filter(key=token_key).first()
if business_token is not None:
business = business_token.business
request.business = business
user = business.owner
request.user = user
return business, None
raise exceptions.AuthenticationFailed('No such user or business')
如您所见,类必须基于来自HTTP请求的令牌传递来验证用户或业务。
如果用户通过API视图中的business令牌进行身份验证,我必须以business.owner
的身份访问request.user
,request.business以business的身份访问www.example.com,但request.user
设置为business,它在某处被覆盖。
1条答案
按热度按时间5kgi1eie1#
二元组的第一项是用户,Django将使用它来设置用户,通过返回
business
,你将把它设置为request.user
,因此你应该返回企业所有者,并设置(仅)request.business
: