Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does SessionAuthentication in Django REST Framework Never Return HTTP401

Looking at the docs and the source of the Django REST Framework, I see that SessionAuthentication only ever returns an HTTP 403 code whereas other Authentication classes will return 401. What is the reason for this?

There are certainly plenty of cases where 401 makes sense.

The issue is especially problematic since " The first authentication class set on the view is used when determining the type of response." and SessionAuthentication is by default the first Authentication class.

like image 464
Alex Rothberg Avatar asked Oct 28 '14 04:10

Alex Rothberg


People also ask

How does IsAuthenticated work in Django?

IsAuthenticated. The IsAuthenticated permission class will deny permission to any unauthenticated user, and allow permission otherwise. This permission is suitable if you want your API to only be accessible to registered users.


Video Answer


1 Answers

Django REST Framework adheres to the HTTP specification, and does not return a 401 response when the Authentication class does not return a WWW-Authenticate header that can be used.

HTTP 401 responses must always include a WWW-Authenticate header, that instructs the client how to authenticate. HTTP 403 responses do not include the WWW-Authenticate header.

-- Django REST Framework documentation

Because the SessionAuthentication class does not define a WWW-Authenticate header that can be used, Django REST Framework cannot return 401 responses and still follow the specification. You can get around this by setting another Authentication class that supports the header to the top of your list, such as BasicAuthentication.

like image 186
Kevin Brown-Silva Avatar answered Oct 25 '22 05:10

Kevin Brown-Silva