[英]How to pass bearer token to raw websocket in Postman
我正在嘗試使用 django 頻道構建聊天應用程序,但是無法找到傳遞不記名令牌的方法
我正在嘗試訪問以下網址:ws://localhost:8000/ws/chat/1/
我熟悉將請求標頭添加到 HTTP 請求,嘗試使用類似的方法(標頭授權作為鍵,承載令牌作為值),嘗試將令牌作為查詢參數傳遞(嘗試 auth=token 和 token=token),嘗試將 40{"token":token} 傳遞給消息。 似乎沒有任何效果。 但也許我做錯了什么?
您需要制作自己的中間件,每次我需要將 jwt 與通道一起使用時,我都在使用這個
from django.db import close_old_connections
from rest_framework_simplejwt.tokens import UntypedToken
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from jwt import decode as jwt_decode
from django.conf import settings
from django.contrib.auth import get_user_model
from channels.db import database_sync_to_async
from channels.middleware import BaseMiddleware
from django.contrib.auth.models import AnonymousUser
@database_sync_to_async
def get_user(validated_token):
try:
user = get_user_model().objects.get(id=validated_token["user_id"])
return user
except User.DoesNotExist:
return AnonymousUser()
class TokenAuthMiddleware():
def __init__(self, inner):
self.inner = inner
async def __call__(self, scope, receive, send, *args, **kwargs):
close_old_connections()
token = dict(scope)['path'].split("token=")[1]
try:
UntypedToken(token)
except (InvalidToken, TokenError) as e:
return None
else:
decoded_data = jwt_decode(token, settings.SECRET_KEY, algorithms=["HS256"])
user = await get_user(decoded_data)
return await self.inner(dict(scope, user=user), receive, send, *args, **kwargs)
這是路徑示例
path('user/token=<str:token>', ChatConsumer.as_asgi()),
或者你可以在cookies中設置token
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.