Introduction to Session Authentication
Session Authentication when used with Django REST Framework allows you to authenticate users very similar to the way Django authenticates users without Django REST Framework.
This will make it extremely easy to introduce a REST API to your web app without having to completely overhaul your authentication system.
The best part of this Authentication Scheme is you literally only have to change ONE line of your Django Application.
Implementation Details (all the little bits…)
settings.py file, just add
'rest_framework.authentication.SessionAuthentication', to your
Now, you will be able to login using the normal Django Framework login views / templates, etc or create your own like I did in my sample application below. Also, here is a post about how I like to create authentication in Django.
If you’d like an example of how this is accomplished, I’ve updated the Django Application I used to show you how to implement Basic Authentication using Django REST Framework. Now, it works using Session Authentication.
How to use this Sample Code
- Unzip the code repository
- Change directory to the unzipped code repository
- Run the command
python manage.py runserver
- Go to http://localhost:8000/polls/ to run the code.
- You’ll be redirected to a very crude login form
adminfor the username and
adminfor the password
- You’ll be redirected to the polls app and application should work.
- Go to http://localhost:8000/accounts/logout to logout of your session.
- Go to http://localhost:8000/polls/api/questions/1 to checkout the API (it should tell you that you’re not authenticated to look at the data).
- Go to http://localhost:8000/accounts/login and login with
adminfor the username and
adminfor the password.
- Go back to http://localhost:8000/polls/api/questions/1 and you should be able to see the data now that you are signed in.
- My login routes, views and templates are found in my
That is the Session Authentication Scheme in a nutshell. I hope you realize how simple it is to implement. Now… for some homework!
Homework (If you’d like…)
- Use the sample application and change the static login form into an AJAX style form. (So, when you put in
adminfor the username and password and click
loginthere should be an AJAX POST request with the username, password and CSRF Token that will attempt to login the user and either send a success message or a failure message. Then, redirect the user back to the
/polls/. If you’re unsure how to add a CSRF Token to all AJAX requests, sign up for my FREE Django REST Framework email course below.)
Want to learn how to Implement Token Authentication in Django REST Framework