我不知道如何使用令牌认证来连接和认证django通道,因为javascript websockets不支持将标头传递到服务器
class TokenAuthMiddleware:
"""
Token authorization middleware for Django Channels 2
"""
def __init__(self, inner):
self.inner = inner
def __call__(self, scope):
headers = dict(scope['headers'])
if b'authorization' in headers:
try:
token_name, token_key = headers[b'authorization'].decode().split()
if token_name == 'Token':
token = Token.objects.get(key=token_key)
scope['user'] = token.user
except Token.DoesNotExist:
scope['user'] = AnonymousUser()
return self.inner(scope)
TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))
我找到了有关使用令牌进行身份验证的答案,但事实是我不知道如何将标头传递给服务器
token = Token.objects.get(key='175f76fd9b63a9477bf5f9a6f2e9a7f12ac62d65')
if token.user:
scope['user'] = token.user
else:
scope['user'] = AnonymousUser()
return self.inner(scope)
TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))
当我手动验证用户身份时,渠道可以识别用户并对其进行身份验证
我尝试过
def get(request):
for user in User.objects.all():
token=Token.objects.get_or_create(user=request.user)
if token.user:
print("ok")
else:
print("not okay")
print(token)
将此功能添加到同一类TokenAuthMiddleware中 我以为这可以用,但是用不上 这样我就可以使用生成的令牌对用户进行身份验证
我只想知道有什么方法可以使用令牌对用户进行身份验证