channels-api icon indicating copy to clipboard operation
channels-api copied to clipboard

Django REST token authentication

Open rbuzu opened this issue 7 years ago • 4 comments

Hi,

I'm trying to implement authentication using tokens generated by django-rest-framework.

Using this gist: https://gist.github.com/leonardoo/9574251b3c7eefccd84fc38905110ce4

I've managed to do this:

Consumer

class APIDemultiplexer(RestTokenConsumerMixin, WebsocketDemultiplexer):
    rest_user = True

    def connect(self, message, **kwargs):
        Group('users').add(message.reply_channel)

        # user here is correct instance of User from given token
        print(message.user)
        Group('users').send({
            'text': json.dumps({
                "accepted": "True",
            })
        })
    consumers = {
        'campaigns': CampaignBinding.consumer
    }

Resource binding

class CampaignBinding(ResourceBinding):

    model = Campaign
    stream = "campaigns"
    serializer_class = CampaignSerializer
    queryset = Campaign.objects.all()
    permission_classes = (AllowAny,)
   
    def get_serializer_context(self):
        # user here is Anonymous
        print(self.user)
        # I need user instance inside self.message
        return {'request': self.message}

My request ws://localhost:8000/?token=ef0ef25fcfc75c0db91bbbccc062f0ab5786dc34

The thing is that I can access User instance only inside Consumer and User instance is not propagated to ResourceBinding. Is there some obvious way to access ser from token inside ResourceBinding?

Any help would be appreciated.

rbuzu avatar Jul 17 '17 14:07 rbuzu

Hi There @rbuzu @linuxlewis I was wondering if you had this figured out.

Stuck with the same issue Thanks a lot!

Robinsondev avatar Sep 12 '17 22:09 Robinsondev

Hi @rbuzu

Problem with channel_session_user attribute of channels.binding.base.Binding class, by default it True, need False.

When channel_session_user = True, binding handler wraps by channels.auth.channel_session_user decorator, and it resets the your token user ;(

gromsterus avatar Oct 22 '17 02:10 gromsterus

Hey @gromsterus

I'm struggling with the same problem. Can we have more details about your solution please ? Thanks a lot

KevinMalot avatar Mar 31 '18 18:03 KevinMalot

Would be adorable of you indeed @gromsterus In need for this feature.

maxblax avatar Jul 24 '18 12:07 maxblax