You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: _posts/2025-07-31-drf-authentication-order-bug.md
+5-5Lines changed: 5 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -25,7 +25,7 @@ toc_label: "DRF Auth Internals"
25
25
toc_icon: "bug"
26
26
---
27
27
28
-
# Introduction
28
+
# The sneaky bug
29
29
30
30
Not all bugs scream at you. Some whisper in 403s.
31
31
@@ -35,7 +35,7 @@ After triple-checking everything and diving deep into DRF’s internals, I found
35
35
36
36
Let me walk you through what happened, what I learned, and why I believe this is a real bug in DRF.
37
37
38
-
# Background: DRF Authentication Flow
38
+
##Background: DRF Authentication Flow
39
39
40
40
In DRF, authentication is handled by a list of classes defined in `DEFAULT_AUTHENTICATION_CLASSES`. Each class tries to authenticate the request, raising `AuthenticationFailed` on failure or returning `None` if it chooses not to act.
41
41
@@ -59,7 +59,7 @@ Because DRF uses the **first** authenticator’s header presence to decide statu
59
59
60
60
The rationale: session first → no header → 403; token-first → header present → 401.
61
61
62
-
# My Setup
62
+
##My Setup
63
63
64
64
I had this configuration:
65
65
@@ -77,7 +77,7 @@ My `BearerAuthentication` inherits from `BaseAuthentication` and returns `"Beare
77
77
78
78
Yet failed bearer requests returned **403**, not **401**-because `SessionAuthentication` came first.
79
79
80
-
# DRF Source Code Digging
80
+
##DRF Source Code Digging
81
81
82
82
In `rest_framework/views.py` (around line 189), DRF handles exceptions like this:
83
83
@@ -139,7 +139,7 @@ Until then, the only reliable workaround is:
139
139
140
140
👉 **Always put the authenticator likely to raise errors (e.g. your BearerAuthentication) *first* in the list, or implement your own exception handler**
141
141
142
-
# Conclusion
142
+
##Conclusion
143
143
144
144
This subtle auth-status behavior can sneakily break API logic or client-side handling. DRF’s current design serves spec compliance-but sacrifices developer intuition when multiple authentication schemes are involved.
0 commit comments