Django admin CSRF 403 error - django

I have multiple django servers (API backend for mobile clients) running behind a load balancer. But when accessing django admin some times I'm getting 403 forbidden error. Is it related to csrf cookie ?
My load balancer setting is,
Session Stickiness - None
Algorithm - Roundrobin

I can't imaging any situation when it's possible until you do all job in one browser tab. When you request form (with GET-request) you generate csrf cookie (if it doesn't exist yet) and generate csrfmiddlewaretoken for this cookie, in response you get both csrf token and cookie value in consistent state. On POST-request your browser send them both and compare on server side. So, this behavior shouldn't depends on backend. But you always can test your assumption with logger. From the documentation:
CSRF failures are logged as warnings to the django.security.csrf
logger.
Changed in Django 1.11:
In older versions, CSRF failures are logged to the django.request logger.

Related

csrf missing error but csrf token is present there i have checked it by inspecting it it is happen in cpanel deployment

Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.
More information is available with DEBUG=True.
In my django project when i deploy it to c panel its form submission giving me error i have already inclued the csrf token and also it is working perfectly fine during the development i did some research they were talking about the render function i have used redirect and i had to use

Using JWT authentication with Django/DRF and Storing JWTs in HttpOnly Cookies

I am trying to build a web app using Django and DRF at the back-end and ReactJs at the front end and I want to keep them separate (i.e. avoid Server Side Rendering).For authentication purposes, I want to employ JWT and I am using djangorestframework-jwt for that. I have read it at several places that it is not secure to store JWTs in the local storage so I am trying to use HttpOnly cookies for that. One can achieve that by configuring the django server to send HttpOnly by overriding the following default settings of the drf-jwt package in the settings.py file of your project JWT_AUTH = { 'JWT_AUTH_COOKIE': '<cookie name>', } which is set to none by default. The server sends the httpOnly cookie as anticipated but there are a few issues I am facing:
1.Same Domain Restraint
I am aware that httpOnly cookies wont be attached to the request headers unless the request is being made to the server which is hosted on the some domain. In my case I am using localhost:8000 for django and localhost:3000 for my react project so the browser doesnt attach the cookie as the request is made to a different port. I tried running both app on port 3000 simultaneously, and the browser did attach the cookie in the header and I did get the a 302 response from the server. However, it opened door to all sorts of problems due domain clash. I reckon I can solve this problem using nginx reverse proxy or something like that but I am not sure about it. Do guide me how can I serve both apps on the same host during the development.
2. Token Refresh Problem
When I refer to the view setup to refresh the token, I run into a bad request error even when the browser does attach the cookie along the request header. This is the server response in the browser
{"token":["This field is required."]}
Thanks if for reading it all the way down here!
In order for things to be secure:
You need CORS (Quickstart: CORS_ALLOWED_HOSTS=["http://localhost:3000"], CORS_ALLOW_CREDENTIALS=True)
The short-lived token (session) cookie (5-15mins), should NOT have HTTP-ONLY setting
The refresh token cookie SHALL have HTTP-ONLY setting
Then your basic flow is:
On login Django creates session token and sends it
Your SPA reads the cookie and adds its value to the authorization header (Authorization: JWT ...token...)
Any request to Django should be made with that Authorization header
The refresh flow is:
Send a request to the refresh token endpoint following the documentation of the library you use
Django then reads the HTTP-ONLY cookie and verifies it
If valid, Django sends a new refresh token as HTTP-ONLY cookie along with a new short-lived token session cookie
Once the refresh token has expired, you log the user out.
An article here goes into detail using GraphQL, but the cookie part and handling of most of the frontend code you should be able to adapt to REST.

Can django #login_required be used on APIs used by a mobile app?

We're using django-notifications-hq to provide users with persistent notifications in our app. Until recently, they lived only in the web app, however now we want to show the notifications in the mobile app as well.
Also, our server is set up with CSRF.
All the endpoints provided by django-notifications-hq use #login_required annotation to verify that user is authenticated.
However, when we're trying to call any of those endpoints from our mobile app, we get 403 response. To be specific, the first OPTIONS request returnd 200, but then the following request for those APIs always results in 403.
This is not a problem when we're using i.e. django-rest-framework's permissions.IsAuthenticated.
The 403 returns this in the response:
<h1>Forbidden <span>(403)</span></h1>
<p>CSRF verification failed. Request aborted.</p>
<p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p>
<p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.</p>
Suggesting it's a CSRF problem, even though mobile app obviously doesn't provide cookies in their requests (it's token-based authorization).
Is this a general issue with #login_required (perhaps it can't be used at all with token-based authorization) or is this some misconfiguration on our part? I couldn't find a clear answer when looking for solutions.
Is there a significant implementation difference between django's #login_required vs django-rest-framework
#permission_classes((permissions.IsAuthenticated,))?

CSRF token is incorrect after login in SPA, but correct after page refresh

We make react SPA with django-rest-framework on backend and use django-rest-auth for user authentication.
When user has logged in, we show him form for change profile data. When user submit this form, we take csrf token from cookie in login response, and put them in request X-CSRFToken header. Server responses that token is missing or incorrect.
If user refreshed the page, and repeated the same actions, csrf token is correct and profile data is updated.
How to solve this problem and why it occurs?
It looks like this is happening:
The login is successful
The cookie+token is created by the CSRF API and returned to the endpoint
The ready state executes some code not executed after the API response
The certificate is validated and the cookie+token is set in the database/app config/server-side cache during a GET request and/or by the ready state callback
Since there is no GET request until the refresh, the cookie+token is not centrally stored until then. Add a request to mimic what happens during the GET, then store it where it is currently being accessed for subsequent requests.
References
Issues with CSRF token and how to solve them | SAP Blogs
Why refresh CSRF token per form request? - Information Security Stack Exchange
CSRF Protection — Flask-WTF 0.14
CSRFGuard 3 Configuration - OWASP
Spring Security: Cross Site Request Forgery (CSRF)
Cross Site Request Forgery protection | Django documentation | Django
XSRF/CSRF Prevention in ASP.NET MVC and Web Pages | Microsoft Docs
Cross-Site Request Forgery is dead!
Still think you don't need HTTPS?

CSRF failure on server using Remote Authentication (works when cookie is cleared)

I'm using Django's RemoteUserMiddleware to authenticate the users in one website. It works great until the next day. When I try to do anything using POST methods (even in Django's admin page) it gives me a 403 error.
I clear the cookies and it starts to work again.
There's a firewall in between my browser and the server which sends the headers to the server (so Django can know who is logged in).
Django's version: 1.9.6
I'm using NGINX in my server
When the error occurs django changes the csrftoken each time. It seems it is getting an Anonymous User when the cache is not cleared...
Any thoughts what could be causing this weird behavior?
This was due one invalid cookie being injected by the system. Django doesn't handle well whenever there is an invalid cookie... it kind wipes some of the keys in the meta tag (where the cookies are checked)