简体   繁体   中英

How to pass bearer token to raw websocket in Postman

I am trying to build a chat application with django channels, however, can't figure a way to pass bearer token

I am trying to reach the following url: ws://localhost:8000/ws/chat/1/

I am familiar with adding request headers to HTTP requests, have tried using similar approaches (header Authorization as a key, and Bearer token as a value), tried passing the token as a query param (tried auth=token and token=token), tried passing 40{"token":token} to the message. Nothing seemed to work. But maybe I am doing something wrong?

You need to make your own middleware, I'm using this one every time I need to use jwt with channels

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)

And here's the path example

path('user/token=<str:token>', ChatConsumer.as_asgi()), Or you can set the token in cookies

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM