How to authenticate a user in a Node application using Django authentication?

My main application is the Django application, however, for some things in real time, I want to use Node / Socket.IO. I use Redis to create a pub / south from Django to Node (and then to various clients). The tricky part is how can I authenticate a Node user against Django auth?

In my Node application, I have:

io.on('connection', function (socket) { const subscribe = redis.createClient(); var userId = authenticateAndGetUserId(); subscribe.subscribe(userId + ':feed-items'); subscribe.on('message', function (channel, message) { socket.emit('feed-items', JSON.parse(message)); }); }); 

So my question is a good strategy for implementing authenticateAndGetUserId ? Sessions are supported in MySQL, so I can go through there. Just curious if there is a better way to do this.

+7
source share
2 answers

On the Django side, I would provide a REST API. Then on Node.js you can do something like POST username / password for

http://yourdjangoserver.com/authenticate

Which will return some JSON with the necessary information. If you want to protect the API from public control, either make it private, or protect it with something like basic auth.

restify is an npm package that simplifies working with REST APIs on the Node.js side. The good thing about this architecture is that it is loosely coupled. You could replace Django with nothing, and the client will never know.

+4
source

Since you already have a redis server, you can store pairs (username, sessionkey) for each registered user, optionally with a TTL value that matches your session settings.

Then, each time a user requests a subscription to a channel, he sends his username, which is then checked on the redis data warehouse.

+2
source

All Articles