django-socket-auth 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Blessed Sam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,387 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-socket-auth
3
+ Version: 0.1.0
4
+ Summary: JWT authentication for Django Channels websockets using djangorestframework-simplejwt
5
+ Author-email: Blessed Sam <oscarblessed04@gmail.com>
6
+ Maintainer-email: Blessed Sam <oscarblessed04@gmail.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/tech-priest-oscar/Django-Socket-Auth
9
+ Project-URL: Documentation, https://github.com/tech-priest-oscar/Django-Socket-Auth#readme
10
+ Project-URL: Repository, https://github.com/tech-priest-oscar/Django-Socket-Auth
11
+ Project-URL: Issues, https://github.com/tech-priest-oscar/Django-Socket-Auth/issues
12
+ Project-URL: Changelog, https://github.com/tech-priest-oscar/Django-Socket-Auth/releases
13
+ Keywords: django,channels,websocket,jwt,simplejwt,authentication
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Environment :: Web Environment
16
+ Classifier: Framework :: Django
17
+ Classifier: Framework :: Django :: 4.2
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Topic :: Internet :: WWW/HTTP
24
+ Classifier: Topic :: Security
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: Django>=4.2
29
+ Requires-Dist: channels>=4.0
30
+ Requires-Dist: djangorestframework>=3.14
31
+ Requires-Dist: djangorestframework-simplejwt>=5.3
32
+ Dynamic: license-file
33
+
34
+ # django-socket-auth
35
+
36
+ Pluggable authentication for [Django Channels](https://channels.readthedocs.io/)
37
+ websocket consumers.
38
+
39
+ Out of the box it authenticates websocket connections with the same access
40
+ tokens your REST API already issues through
41
+ [djangorestframework-simplejwt](https://django-rest-framework-simplejwt.readthedocs.io/),
42
+ so clients log in once and use one token for both HTTP and websockets. You can
43
+ also plug in your own authentication: return a user and it goes into
44
+ `scope["user"]`.
45
+
46
+ - Works with the default Django user model or any custom one
47
+ - Bring your own auth with a small backend class (sync or async)
48
+ - Accepts the token in a header **or** the query string (for browsers)
49
+ - Respects your existing `SIMPLE_JWT` settings
50
+ - No models, no migrations, nothing to add to `INSTALLED_APPS`
51
+
52
+ ## Requirements
53
+
54
+ - Python 3.10+
55
+ - Django 4.2+
56
+ - Channels 4.0+
57
+ - djangorestframework-simplejwt 5.3+
58
+
59
+ ## Installation
60
+
61
+ ```bash
62
+ pip install git+https://github.com/tech-priest-oscar/Django-Socket-Auth.git
63
+ ```
64
+
65
+ Your project needs simplejwt set up to issue tokens. If it isn't already, add
66
+ its views to your `urls.py`:
67
+
68
+ ```python
69
+ from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
70
+
71
+ urlpatterns = [
72
+ path("api/token/", TokenObtainPairView.as_view()),
73
+ path("api/token/refresh/", TokenRefreshView.as_view()),
74
+ ]
75
+ ```
76
+
77
+ ## Quick start
78
+
79
+ ### 1. Wrap your websocket routes with the middleware
80
+
81
+ ```python
82
+ # asgi.py
83
+ import os
84
+
85
+ from channels.routing import ProtocolTypeRouter, URLRouter
86
+ from django.core.asgi import get_asgi_application
87
+
88
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
89
+ django_asgi_app = get_asgi_application()
90
+
91
+ # Import anything that touches models *after* get_asgi_application()
92
+ from django_socket_auth.middleware import SocketAuthMiddleware
93
+ from myapp.routing import websocket_urlpatterns
94
+
95
+ application = ProtocolTypeRouter({
96
+ "http": django_asgi_app,
97
+ "websocket": SocketAuthMiddleware(URLRouter(websocket_urlpatterns)),
98
+ })
99
+ ```
100
+
101
+ ### 2. Subclass an authenticated consumer
102
+
103
+ ```python
104
+ # myapp/consumers.py
105
+ from django_socket_auth.consumers import AuthenticatedJsonWebsocketConsumer
106
+
107
+
108
+ class ChatConsumer(AuthenticatedJsonWebsocketConsumer):
109
+ async def authenticated_connect(self):
110
+ # Only called for authenticated users. self.user is already set.
111
+ await self.accept()
112
+ await self.send_json({"hello": self.user.get_username()})
113
+
114
+ async def receive_json(self, content):
115
+ ...
116
+ ```
117
+
118
+ Override `authenticated_connect()` instead of `connect()`. The default
119
+ implementation just calls `self.accept()`.
120
+
121
+ ### 3. Connect from a client
122
+
123
+ ```js
124
+ // Browsers can't set headers on websockets, so pass the token in the URL.
125
+ const socket = new WebSocket(`wss://example.com/ws/chat/?token=${accessToken}`);
126
+
127
+ socket.addEventListener("close", (event) => {
128
+ if (event.code === 4001) {
129
+ // Not authenticated: refresh the access token and reconnect.
130
+ }
131
+ });
132
+ ```
133
+
134
+ From a non-browser client, prefer a header:
135
+
136
+ ```python
137
+ import websockets
138
+
139
+ async with websockets.connect(
140
+ "wss://example.com/ws/chat/",
141
+ additional_headers={"Authorization": f"Bearer {access_token}"},
142
+ ) as ws:
143
+ ...
144
+ ```
145
+
146
+ ## How it works
147
+
148
+ ### Middleware
149
+
150
+ `SocketAuthMiddleware` asks each configured backend, in order, to authenticate
151
+ the connection. The first authenticated user returned is put in
152
+ `scope["user"]`. A backend that returns `None` or `AnonymousUser` has failed,
153
+ and the next backend is tried. If every backend fails, `scope["user"]` is set
154
+ to `AnonymousUser`.
155
+
156
+ The default backend, `SimpleJWTBackend`, reads the access token from the
157
+ handshake, in this order:
158
+
159
+ 1. `Authorization: Bearer <access>` header
160
+ 2. `?token=<access>` query string
161
+
162
+ It then validates the token with simplejwt. If the token is missing,
163
+ malformed, expired, the wrong type (for example a refresh token), or belongs to
164
+ an inactive or deleted user, it returns no user.
165
+
166
+ The middleware never rejects a connection by itself. That is up to the
167
+ consumer, so you can still serve anonymous users on some routes if you want.
168
+
169
+ ### Consumers
170
+
171
+ | Class | Use it for |
172
+ |---|---|
173
+ | `AuthenticatedWebsocketConsumer` | Text or bytes messages (`AsyncWebsocketConsumer`) |
174
+ | `AuthenticatedJsonWebsocketConsumer` | JSON messages (`AsyncJsonWebsocketConsumer`) |
175
+ | `SocketAuthConsumerMixin` | Adding the check to your own consumer base class |
176
+
177
+ Unauthenticated connections are accepted and then immediately closed with
178
+ code **4001**, so the client can tell an auth failure apart from other errors.
179
+ To use a different code, set `unauthenticated_close_code` on your consumer:
180
+
181
+ ```python
182
+ class ChatConsumer(AuthenticatedJsonWebsocketConsumer):
183
+ unauthenticated_close_code = 4003
184
+ ```
185
+
186
+ To use the mixin with your own base class, put it first:
187
+
188
+ ```python
189
+ from channels.generic.websocket import AsyncWebsocketConsumer
190
+ from django_socket_auth.consumers import SocketAuthConsumerMixin
191
+
192
+
193
+ class MyBaseConsumer(SocketAuthConsumerMixin, AsyncWebsocketConsumer):
194
+ ...
195
+ ```
196
+
197
+ ## Custom authentication
198
+
199
+ A backend is a class with an `authenticate(scope)` method. Return a user to
200
+ authenticate the connection, or `None` to let the next backend try.
201
+
202
+ `authenticate` can be a normal method or an `async def`. Normal methods run in
203
+ a worker thread, so you can use the Django ORM directly.
204
+
205
+ ### Backend interface
206
+
207
+ These are the methods the package calls. Subclassing `BaseBackend` or
208
+ `TokenBackend` is optional: any class with an `authenticate(scope)` method
209
+ works.
210
+
211
+ **`BaseBackend`**: implement your own authentication from scratch.
212
+
213
+ | Method | Required | Receives | Must return |
214
+ |---|---|---|---|
215
+ | `authenticate(self, scope)` | Yes | The ASGI connection [`scope`](https://asgi.readthedocs.io/en/latest/specs/www.html#websocket-connection-scope) dict | A user object, or `None` |
216
+
217
+ **`TokenBackend`**: the package finds the token; you check it.
218
+
219
+ | Method | Required | Receives | Must return |
220
+ |---|---|---|---|
221
+ | `authenticate_token(self, token)` | Yes | The raw token string (never empty) | A user object, or `None` |
222
+ | `get_raw_token(self, scope)` | No (override to read the token from elsewhere) | The ASGI connection `scope` dict | The token string, or `None` |
223
+
224
+ Do not override `authenticate` on a `TokenBackend`. It is what calls
225
+ `get_raw_token` and then `authenticate_token`.
226
+
227
+ Each method can be a normal `def` or an `async def`.
228
+
229
+ #### Rules for every backend
230
+
231
+ - **Return `None` (or `AnonymousUser()`) when you can't authenticate the
232
+ connection.** Both count as a failed attempt, and the next backend is tried.
233
+ - **Don't raise for a bad or missing credential.** Return `None` instead. An
234
+ exception raised from a backend is not caught, so the connection fails with a
235
+ server error instead of being closed with `4001`.
236
+ - **Don't store per-connection data on `self`.** One instance of each backend
237
+ is created when the middleware is built and shared by every connection,
238
+ including connections handled at the same time.
239
+ - **The user you return is put into `scope["user"]` as is.** The consumers
240
+ check `user.is_authenticated`, so return a real user model instance (or any
241
+ object with `is_authenticated = True`).
242
+
243
+ #### Full sample
244
+
245
+ ```python
246
+ # myapp/socket_auth.py
247
+ from django_socket_auth.backends import BaseBackend, TokenBackend
248
+
249
+ from myapp.models import ApiKey
250
+
251
+
252
+ class MyBackend(BaseBackend):
253
+ """Your own authentication, from scratch."""
254
+
255
+ def authenticate(self, scope):
256
+ """
257
+ scope["headers"] -> list of (name, value) byte pairs, names lower-case
258
+ scope["query_string"] -> raw query string bytes, e.g. b"token=abc"
259
+ scope["path"] -> e.g. "/ws/chat/"
260
+ scope["client"] -> (ip, port)
261
+
262
+ Return a user to authenticate the connection, or None to let the next
263
+ backend try.
264
+ """
265
+ headers = dict(scope["headers"])
266
+ api_key = headers.get(b"x-api-key", b"").decode("latin1")
267
+ if not api_key:
268
+ return None
269
+ key = ApiKey.objects.select_related("user").filter(key=api_key).first()
270
+ return key.user if key else None
271
+
272
+
273
+ class MyTokenBackend(TokenBackend):
274
+ """The token comes from `Authorization: Bearer ...` or `?token=...`."""
275
+
276
+ def authenticate_token(self, token):
277
+ """`token` is the raw token string. Return its user, or None."""
278
+ key = ApiKey.objects.select_related("user").filter(key=token).first()
279
+ return key.user if key else None
280
+
281
+ # Optional: only if the token lives somewhere else.
282
+ # def get_raw_token(self, scope):
283
+ # return dict(scope["headers"]).get(b"x-api-key", b"").decode() or None
284
+
285
+
286
+ class MyAsyncTokenBackend(TokenBackend):
287
+ """Same as above, written with `async def`."""
288
+
289
+ async def authenticate_token(self, token):
290
+ key = await ApiKey.objects.select_related("user").filter(key=token).afirst()
291
+ return key.user if key else None
292
+ ```
293
+
294
+ Then turn it on (see [Turning backends on](#turning-backends-on)):
295
+
296
+ ```python
297
+ SOCKET_AUTH_BACKENDS = ["myapp.socket_auth.MyTokenBackend"]
298
+ ```
299
+
300
+ ### Use your own auth: return a user
301
+
302
+ Subclass `BaseBackend` when you already have a way to work out the user, for
303
+ example from a session, a signed cookie or another service:
304
+
305
+ ```python
306
+ from django_socket_auth.backends import BaseBackend
307
+
308
+ from myapp.auth import user_from_cookie
309
+
310
+
311
+ class MyCookieBackend(BaseBackend):
312
+ def authenticate(self, scope):
313
+ headers = dict(scope["headers"])
314
+ return user_from_cookie(headers.get(b"cookie", b"")) # user or None
315
+ ```
316
+
317
+ ### Reuse the token handling: check the token yourself
318
+
319
+ Subclass `TokenBackend` when clients send a token, but it isn't a simplejwt
320
+ token (for example an API key or a token from another provider). It reads
321
+ the token from the header or query string for you; you only turn it into a
322
+ user:
323
+
324
+ ```python
325
+ from django_socket_auth.backends import TokenBackend
326
+
327
+ from myapp.models import ApiKey
328
+
329
+
330
+ class ApiKeyBackend(TokenBackend):
331
+ def authenticate_token(self, token):
332
+ key = ApiKey.objects.select_related("user").filter(key=token).first()
333
+ return key.user if key else None
334
+ ```
335
+
336
+ `authenticate_token` can also be `async def`. To read the token from somewhere
337
+ else, override `get_raw_token(scope)` as well.
338
+
339
+ ### Turning backends on
340
+
341
+ For the whole project, in `settings.py`:
342
+
343
+ ```python
344
+ SOCKET_AUTH_BACKENDS = [
345
+ "myapp.socket_auth.ApiKeyBackend",
346
+ "django_socket_auth.backends.SimpleJWTBackend", # keep JWT working too
347
+ ]
348
+ ```
349
+
350
+ Or for one set of routes, when building the middleware:
351
+
352
+ ```python
353
+ SocketAuthMiddleware(URLRouter(websocket_urlpatterns), auth_backends=[ApiKeyBackend])
354
+ ```
355
+
356
+ `auth_backends` takes dotted paths, classes or instances. Passing it overrides
357
+ `SOCKET_AUTH_BACKENDS` for that middleware.
358
+
359
+ ## Configuration
360
+
361
+ | Setting | Default | |
362
+ |---|---|---|
363
+ | `SOCKET_AUTH_BACKENDS` | `["django_socket_auth.backends.SimpleJWTBackend"]` | Backends to try, in order |
364
+
365
+ `SimpleJWTBackend` validates tokens with your project's
366
+ [`SIMPLE_JWT` settings](https://django-rest-framework-simplejwt.readthedocs.io/en/latest/settings.html)
367
+ (signing key, algorithm, token lifetimes, user ID claim, and so on).
368
+
369
+ ## Security notes
370
+
371
+ - **Query-string tokens can end up in logs.** Proxies and servers often log
372
+ full URLs. Keep access tokens short-lived, or use a header where the client
373
+ supports it.
374
+ - **Use `wss://` in production** so tokens are not sent in plain text.
375
+ - **The user is checked once, at connect time.** A connection stays open after
376
+ its token expires. Close long-lived connections yourself if that matters.
377
+
378
+ ## Development
379
+
380
+ ```bash
381
+ python -m venv venv
382
+ venv/bin/pip install -r requirements.txt
383
+ make pre-commit-install
384
+
385
+ make test # run the test suite
386
+ make pre-commit # format and lint everything
387
+ ```