Django Rest Framework will not accept my CSRF Token - python

I'm trying to build a Single Page Application with Django Rest Framework. For authentication, I'm using a login view that initiates a session and requires csrf protection on all api routes. Because there is no templating going on, the csrf_token tag is never used, so I have to manually get the token with get_token. Instead of putting it in the main index file that will be given in the home view, I want to set it on its own cookie. No this is not the CSRF Cookie that django provides, as that one has the CSRF secret, plus I mentioned I'm using sessions, so the secret is stored there. This cookie will have the token which will be used for all mutating requests.
I have tried everything to get django to accept the cookie but nothing has worked. I can login just fine the first time, because there was no previous session, but anything after that just throws an error 403. I tried using ensure_csrf_cookie but that didn't help. I tried without sessions and still nothing. I even tried rearranging the middleware order and still nothing. I even tried my own custom middleware to create the cookie but it didn't work. Here's the code that I have ended up with as of now:
views.py
#api_view(http_method_names = ["GET"])
def home(request):
"""API route for retrieving the main page of web application"""
return Response(None, status = status.HTTP_204_NO_CONTENT);
class LoginView(APIView):
"""API endpoint that allows users to login"""
def post(self, request, format = None):
"""API login handler"""
user = authenticate(username = request.data["username"], password = request.data['password']);
if user is None:
raise AuthenticationFailed;
login(request, user);
return Response(UserSerializer(user).data);
class LogoutView(APIView):
"""API endpoint that allows users to logout of application"""
def post(self, request, format = None):
logout(request);
return Response(None, status = status.HTTP_204_NO_CONTENT);
settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware'
]
# Sessions
SESSION_ENGINE = "django.contrib.sessions.backends.file"
SESSION_FILE_PATH = os.getenv("DJANGO_SESSION_FILE_PATH")
SESSION_COOKIE_AGE = int(os.getenv("SESSION_LIFETIME")) * 60
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_NAME = os.getenv("SESSION_COOKIE")
SESSION_COOKIE_SECURE = os.getenv("APP_ENV") != "local"
# CSRF
CSRF_USE_SESSIONS = True
# the following setting is for the csrf token only, not for the CSRF secret, which is the default for django
CSRF_TOKEN_CARRIER = os.getenv("XSRF_COOKIE")
CSRF_HEADER_NAME = "X-XSRF-TOKEN"
CSRF_COOKIE_SECURE = SESSION_COOKIE_SECURE
CSRF_COOKIE_AGE = SESSION_COOKIE_AGE
CSRF_TOKEN_HTTPONLY = False
REST_FRAMEWORK = {
"EXCEPTION_HANDLER":"django_app.application.exceptions.global_exception_handler",
"DEFAULT_AUTHENTICATION_CLASSES":[
"rest_framework.authentication.SessionAuthentication"
]
}
this was the custom middleware I wrote but I'm not using right now:
"""Custom CSRF Middleware for generating CSRF cookies"""
from django.conf import settings;
from django.middleware.csrf import CsrfViewMiddleware, rotate_token, get_token;
class CSRFCookieMiddleware:
"""Sets CSRF token cookie for ajax requests"""
def __init__(self, get_response):
self.get_response = get_response;
def __call__(self, request):
response = self.get_response(request);
if settings.CSRF_USE_SESSIONS:
response.set_cookie(
settings.CSRF_TOKEN_CARRIER,
get_token(request),
max_age=settings.CSRF_COOKIE_AGE,
domain=settings.CSRF_COOKIE_DOMAIN,
path=settings.CSRF_COOKIE_PATH,
secure=settings.CSRF_COOKIE_SECURE,
httponly=settings.CSRF_COOKIE_HTTPONLY,
samesite=settings.CSRF_COOKIE_SAMESITE,
);
return response;
the error 403 response:
HTTP/1.1 403 Forbidden
Date: Thu, 25 Apr 2019 17:11:28 GMT
Server: WSGIServer/0.2 CPython/3.7.0
Content-Type: application/json
Vary: Accept, Cookie
Allow: POST, OPTIONS
X-Frame-Options: SAMEORIGIN
Content-Length: 59
{
"message": "CSRF Failed: CSRF token missing or incorrect."
}
this is the http request I use in my REST client in vs code:
POST http://electro:8000/api/logout
X-XSRF-TOKEN: JFaygAm49v6wChT6CcUJaeLwq53YwzAlnEZmoE0m21cg9xLCnZGvTt6oM9MKbvV8
Cookie: electro=nzzv64gymt1aqu4whdhax1s9t91c3m58
I cannot believe how hard it is to tweak frameworks to work with single page apps when there's plenty support for static websites and APIs. So where have I gone wrong?

I finally figured out what happened. Buried deep in the django documentation, I found out that the CSRF_HEADER_NAME setting has a specific syntax/format:
# default value
CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN";
so to fix this, the docs literally say that for my case I must set the value, according to my preferences, like so:
CSRF_HEADER_NAME = "HTTP_X_XSRF_TOKEN";
So now it can accept the token at X-XSRF-TOKEN header, along with session cookie. But since I'm using sessions with csrf, I must use the custom middleware I created (see question) to set the csrf token cookie manually. This is because ensure_csrf_cookie apparently only throws you the session cookie.
Lastly, if you need to protect the login route, since I'm using SessionAuthentication, I will need the custom middleware, ensure_csrf_cookie, and csrf_protect so that I can get a starting session with csrf token and then submit those when logging in:
#api_view(http_method_names = ["GET"])
#ensure_csrf_cookie
def home(request):
"""API route for retrieving the main page of web application"""
return Response(None, status = status.HTTP_204_NO_CONTENT);
#method_decorator(csrf_protect, 'dispatch')
#method_decorator(ensure_csrf_cookie, 'dispatch')
class LoginView(APIView):
"""API endpoint that allows users to login"""
def post(self, request, format = None):
"""API login handler"""
user = authenticate(username = request.data["username"], password = request.data['password']);
if user is None:
raise AuthenticationFailed;
login(request, user);
return Response(UserSerializer(user).data);
may this help whoever is building a Single Page App backend with django

The documentation seems to be misleading regarding the replacement of hyphen to underscores.
It states:
Default: 'HTTP_X_CSRFTOKEN'
The name of the request header used for CSRF authentication.
As with other HTTP headers in request.META, the header name received from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores, and adding an 'HTTP_' prefix to the name. For example, if your client sends a 'X-XSRF-TOKEN' header, the setting should be 'HTTP_X_XSRF_TOKEN'.
I was using fetch, which lowercases all header names.
I named my client side header 'X_CSRFTOKEN', which got sent out as 'x_csrftoken'.
The request did not work until I changed the name to 'x-csrftoken'.
I found a line in Django that converts underscores to hyphens, which may be the problem.
tl;dr: To match Django's default HTTP_X_CSRFTOKEN, name your client header x-csrftoken.

Related

Python Requests with Django Rest Framework - 'detail': 'Authentication credentials were not provided'

I've got a tiny function that just looks to get a response from my DRF API Endpoint.
My DRF settings look like this:
"DEFAULT_AUTHENTICATION_CLASSES": [
# Enabling this it will require Django Session (Including CSRF)
"rest_framework.authentication.SessionAuthentication"
],
"DEFAULT_PERMISSION_CLASSES": [
# Globally only allow IsAuthenticated users access to API Endpoints
"rest_framework.permissions.IsAuthenticated"
],
I'm using this to try and hit the endpoint:
def get_car_details(car_id):
headers = {"X-Requested-With": "XMLHttpRequest"}
api_app = "http://localhost:8000/"
api_model = "cars/"
response = requests.get(api_app + api_model + str(car_id), headers=headers)
json_response = response.json()
return json_response
I keep getting 'detail': 'Authentication credentials were not provided'
Do I need to generate a CSRF token and include it in a GET request? The only time this gets hit is when a user goes to a view that requires they are logged in. Is there a way to pass that logged-in user to the endpoint??
When you make your request from the get_car_details function you need to be sure that the request is authenticated. This does not look like a CSRF issue.
When using session based authentication a session cookie is passed back after logging in. So before you call get_car_details you would need to first make a request to login, keep that session, and use that session when calling the API.
Requests has a session class requests.Session() that you can use for this purpose. Details here: https://docs.python-requests.org/en/latest/user/advanced/
Many people find token based authentication easier partly a session cookie does not need to be maintained.

How to add a filter in django for every request?

I want to add a security filter so that every request to my django app will go through the filter first and then let the request go through if the token from the header is valid.
How can I accomplish that in django?
Thanks.
You can add a new middleware like this:
class SecurityMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
token = request.META.get('HTTP_AUTHORIZATION')
if token != "Some Value":
return HttpResponse('Unauthorized', status=401)
response = self.get_response(request)
return response
Then add this to the MIDDLEWARE in settings.py.
MIDDLEWARE = [
...
'path.to.SecurityMiddleware'
]
More information can be found in custom middleware documentation and request and response object documentation.
FYI, if you want to implement a standard authentication system like JWT or basic auths, consider using thrid party libraries like Simple JWT with Django Rest Framework or so on.

Token in query string with Django REST Framework's TokenAuthentication

In an API built with Django REST Framework authentication can be done using the TokenAuthentication method. Its documentation says the authentication token should be sent via an Authorization header.
Often one can send API-keys or tokens via a query string in order to authenticate, like https://domain.com/v1/resource?api-key=lala.
Is there a way to do the same with Django REST Framework's TokenAuthentication?
By default DRF doesn't support query string to authenticate, but you can easily override their authenticate method in TokenAuthentication class to support it.
An example would be:
class TokenAuthSupportQueryString(TokenAuthentication):
"""
Extend the TokenAuthentication class to support querystring authentication
in the form of "http://www.example.com/?auth_token=<token_key>"
"""
def authenticate(self, request):
# Check if 'token_auth' is in the request query params.
# Give precedence to 'Authorization' header.
if 'auth_token' in request.query_params and \
'HTTP_AUTHORIZATION' not in request.META:
return self.authenticate_credentials(request.query_params.get('auth_token'))
else:
return super(TokenAuthSupportQueryString, self).authenticate(request)
class QueryStringBasedTokenAuthentication(TokenAuthentication):
def authenticate(self, request):
key = request.query_params.get('auth_token').strip()
if key:
return self.authenticate_credentials(key)
return False
DRF has TokenAuthentication which looks for token in header. The method authenticate_credentials takes care verifying the token.
As of 2018 using Django Rest Framework you can create your own Authentication class see http://getblimp.github.io/django-rest-framework-jwt/#extending-jsonwebtokenauthentication
class JSONWebTokenAuthenticationQS(BaseJSONWebTokenAuthentication):
def get_jwt_value(self, request):
return request.QUERY_PARAMS.get('jwt')
Then in the APIView class add
authentication_classes = (JSONWebTokenAuthenticationQS,)
Or
#authentication_classes((JSONWebTokenAuthenticationQS,))
On the view function.
Following up on Scott Warren's answer. That was a step in the right direction, because the DRFJWT docs don't include the important authentication_classes line. But with that, as noted in Issue 441 there is a big problem that you can't mix the JWT authentication methods. I ended up with:
class JSONWebTokenAuthenticationQS(JSONWebTokenAuthentication):
def get_jwt_value(self, request):
return request.GET.get('jwt') or JSONWebTokenAuthentication.get_jwt_value(self, request)
which so far seems to work well. It uses JSONWebTokenAuthentication instead of the Base class, because it has to in order to use the original get_jwt_value method.
refer answer of OmriToptix and Scott Warren and others website 1 and 2
for now most case use JSONWebTokenAuthentication, so now should override its get_jwt_value, full code is:
# from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import get_authorization_header
class JWTAuthByQueryStringOrHeader(JSONWebTokenAuthentication):
# class JWTAuthByQueryStringOrHeader(BaseJSONWebTokenAuthentication):
"""
Extend the TokenAuthentication class to support querystring authentication
in the form of "http://www.example.com/?jwt_token=<token_key>"
"""
def get_jwt_value(self, request):
# Check if 'jwt_token' is in the request query params.
# Give precedence to 'Authorization' header.
queryParams = request.query_params
reqMeta = request.META
if ('jwt_token' in queryParams) and ('HTTP_AUTHORIZATION' not in reqMeta):
jwt_token = queryParams.get('jwt_token')
# got jwt token from query parameter
return jwt_token
else:
# call JSONWebTokenAuthentication's get_jwt_value
# to get jwt token from header of 'Authorization'
return super(JWTAuthByQueryStringOrHeader, self).get_jwt_value(request)
here save above code to apps/util/jwt_token.py, then NOT FORGET add related Django settings:
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'apps.util.jwt_token.JWTAuthByQueryStringOrHeader',
...
),
...
}
now frontend/web side can call api like this:
http://localhost:65000/api/v1/scripts/3d9e77b0-e538-49b8-8790-60301ca79e1d/script_word_export/?jwt_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWVkMGEwZDgtMmFiYi00MDFkLTk5NTYtMTQ5MzcxNDIwMGUzIiwidXNlcm5hbWUiOiJsc2R2aW5jZW50IiwiZXhwIjoxNTMxOTAyOTU0LCJlbWFpbCI6InZpbmNlbnQuY2hlbkBuYXR1cmxpbmcuY29tIn0.wheM7Fmv8y8ysz0pp-yUHFqfk-IQ5a8n_8OplbYkj7s
to pass jwt_token into server side, get authorized to download/export the file.
while still support original method pass jwt token inside header 'Authorization':
POST http://localhost:65000/api/v1/scripts/3d9e77b0-e538-49b8-8790-60301ca79e1d/script_word_export/
Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWVkMGEwZDgtMmFiYi00MDFkLTk5NTYtMTQ5MzcxNDIwMGUzIiwidXNlcm5hbWUiOiJsc2R2aW5jZW50IiwiZXhwIjoxNTMxOTAyOTU0LCJlbWFpbCI6InZpbmNlbnQuY2hlbkBuYXR1cmxpbmcuY29tIn0.wheM7Fmv8y8ysz0pp-yUHFqfk-IQ5a8n_8OplbYkj7s

How to enable basic access authentication in django

I want to enable basic access authentication in my Django project like this:
I found this post by Google, and changed my settings.py following the first answer:
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
...
)
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.RemoteUserBackend',
)
But the authentication window doesn't come out. The project is still in debug mode and I run it by python ./manage.py runserver.
I can think of multiple ways to do this. If you want your entire django application protected by basic authentication then you can add an authentication middleware to your wsgi app. Django creates a default wsgi application in your project. Add the following middleware to this wsgi.py file:
class AuthenticationMiddleware(object):
def __init__(self, app, username, password):
self.app = app
self.username = username
self.password = password
def __unauthorized(self, start_response):
start_response('401 Unauthorized', [
('Content-type', 'text/plain'),
('WWW-Authenticate', 'Basic realm="restricted"')
])
return ['You are unauthorized and forbidden to view this resource.']
def __call__(self, environ, start_response):
authorization = environ.get('HTTP_AUTHORIZATION', None)
if not authorization:
return self.__unauthorized(start_response)
(method, authentication) = authorization.split(' ', 1)
if 'basic' != method.lower():
return self.__unauthorized(start_response)
request_username, request_password = authentication.strip().decode('base64').split(':', 1)
if self.username == request_username and self.password == request_password:
return self.app(environ, start_response)
return self.__unauthorized(start_response)
Then, instead of calling
application = get_wsgi_application()
You should use:
application = AuthenticationMiddleware(application, "myusername", "mypassword")
This will ensure that every request to your django server goes through basic authentication.
Please note that unless you're using HTTPS then basic authentication isn't secure and the user credentials will not be encrypted.
If you only want some of your views to be covered by basic authentication then you can modify the above class to be a function decorator :
def basic_auth_required(func):
#wraps(func)
def _decorator(request, *args, **kwargs):
from django.contrib.auth import authenticate, login
if request.META.has_key('HTTP_AUTHORIZATION'):
authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
if authmeth.lower() == 'basic':
auth = auth.strip().decode('base64')
username, password = auth.split(':', 1)
if username=='myusername' and password == 'my password':
return func(request, *args, **kwargs)
else:
return HttpResponseForbidden('<h1>Forbidden</h1>')
res = HttpResponse()
res.status_code = 401
res['WWW-Authenticate'] = 'Basic'
return res
return _decorator
Then you can decorate your views with this to activate basic authentication.
Note that the username/password are both hardcoded in the examples above. You can replace that with your own mechanism.
Hope this helps
As mentioned in the docs, the REMOTE_USER is set by the web server. Typically you will need to configure a web server like Apache or IIS to protect a site or a directory using HTTP Basic Authentication.
For debug purposes, I suggest setting a dummy user in the manage.py, say:
import os
from django.conf import settings
if settings.DEBUG:
os.environ['REMOTE_USER'] = "terry"

Using Requests python library to connect Django app failed on authentication

Maybe a stupid question here:
Is Requests(A python HTTP lib) support Django 1.4 ?
I use Requests follow the Official Quick Start like below:
requests.get('http://127.0.0.1:8000/getAllTracks', auth=('myUser', 'myPass'))
but i never get authentication right.(Of course i've checked the url, username, password again and again.)
The above url 'http://127.0.0.1:8000/getAllTracks' matches an url pattern of the url.py of a Django project, and that url pattern's callback is the 'getAllTracks' view of a Django app.
If i comment out the authentication code of the 'getAllTracks' view, then the above code works OK, but if i add those authentication code back for the view, then the above code never get authenticated right.
The authentication code of the view is actually very simple, exactly like below (The second line):
def getAllTracks(request):
if request.user.is_authenticated():
tracks = Tracks.objects.all()
if tracks:
# Do sth. here
Which means if i delete the above second line(with some indents adjustments of course), then the requests.get() operation do the right thing for me, but if not(keep the second line), then it never get it right.
Any help would be appreciated.
In Django authentication works in following way:
There is a SessionMiddleware and AuthenticationMiddleware. The process_request() of both these classes is called before any view is called.
SessionMiddleware uses cookies at a lower level. It checks for a cookie named sessionid and try to associate this cookie with a user.
AuthenticationMiddleware checks if this cookie is associated with an user then sets request.user as that corresponding user. If the cookie sessionid is not found or can't be associated with any user, then request.user is set to an instance of AnonymousUser().
Since Http is a stateless protocol, django maintains session for a particular user using these two middlewares and using cookies at a lower level.
Coming to the code, so that requests can work with django.
You must first call the view where you authenticate and login the user. The response from this view will contain sessionid in cookies.
You should use this cookie and send it in the next request so that django can authenticate this particular user and so that your request.user.is_authenticated() passes.
from django.contrib.auth import authenticate, login
def login_user(request):
user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))
if user:
login(request, user)
return HttpResponse("Logged In")
return HttpResponse("Not Logged In")
def getAllTracks(request):
if request.user.is_authenticated():
return HttpResponse("Authenticated user")
return HttpResponse("Non Authenticated user")
Making the requests:
import requests
resp = requests.post('http://127.0.0.1:8000/login/', {'username': 'akshar', 'password': 'abc'})
print resp.status_code
200 #output
print resp.content
'Logged In' #output
cookies = dict(sessionid=resp.cookies.get('sessionid'))
print cookies
{'sessionid': '1fe38ea7b22b4d4f8d1b391e1ea816c0'} #output
response_two = requests.get('http://127.0.0.1:8000/getAllTracks/', cookies=cookies)
Notice that we pass cookies using cookies keyword argument
print response_two.status_code
200 #output
print response_two.content
'Authenticated user' #output
So, our request.user.is_authenticated() worked properly.
response_three = requests.get('http://127.0.0.1:8000/hogwarts/getAllTracks/')
Notice we do not pass the cookies here.
print response_three.content
'Non Authenticated user' #output
I guess, auth keyword for Requests enables HTTP Basic authentication which is not what is used in Django. You should make a POST request to login url of your project with username and password provided in POST data, after that your Requests instance will receive a session cookie with saved authentication data and will be able to do successful requests to auth-protected views.
Might be easier for you to just set a cookie on initial authentication, pass that back to the client, and then for future requests expect the client to send back that token in the headers, like so:
r = requests.post('http://127.0.0.1:8000', auth=(UN, PW))
self.token = r.cookies['token']
self.headers = {'token': token}
and then in further calls you could, assuming you're in the same class, just do:
r = requests.post('http://127.0.0.1:8000/getAllTracks', headers=self.headers)

Categories

Resources