next.js app how to prevent XSS and CSRF attacks? - xss

Basically I am building a serverless next.js app with mongodb.
Idea 1 : React prevents most of the XSS already , so should I just store user login info in web storage ? this way I do not need to worry about CSRF.
Idea 2 : If I use httpOnly cookie based auth , since httpOnly and sameorigin already prevents XSS(and some CSRF), I can proceed with my design without worries ? do you think it is enough for a beginner eCommerce site ?
Idea 3: Add a CSRF token to the cookie based auth
user logged in , in the /api/login, I check for username/password then generate a cookie with CSRF token in it and also res.end(CSRF). after receiving this , we store CSRF in useContext to make it available for all components.
so whenever i fetch with POST i attach this global CSRF token to the req.body , lastly , in /api/ we compare this CSRF in the req.body with CSRF in the cookie .
is there any better ideas for serverless app ? or am i missing something ? what do you recommend ?
idea 4: use CSRF built-in framework like express.js ....
UPDATED : next-auth is supported , but i want to learn about auth so really want to build on on my own

Related

Django Frontend Autho key and refresh key

I would like to separate my Django frontend and backend. Literally creating 2 Django servers.
What is the best way to store auth access-token and refresh-token on frontend?
What is the best way to validate auth when API is called?
Thanks!
Read about storing jwt on frontend here :
Should JWT be stored in localStorage or cookie?
Basically, there can be two ways, either storing it in localstorage or HTTP Cookie. Read about pros and cons of both approach and decide what suits you best.
In API, it's best to pass access token in header of request and validating the same using a Django Middleware. Send a refresh request from your frontend if the reponse returns an Unauthorized error and error message something like "Token Expired", which will be created by you on the backend. See this package for more :
https://django-rest-framework-simplejwt.readthedocs.io/en/latest/

How to implement token authentication using httponly cookie in Django and Drf

I'm building an application with django , Drf and currently using vanilla JS as Frontend for now.
I searched almost all through web on different use case for authentication on the web and I found out different links but these links seem to always favour the session authentication and token authentication.
Using Django helps us with the session authentication as default so I decided to study the auth process using a token auth.
While doing this, I initially used the localstorage as a store for my tokens gotten from the backend response after user authenticates, But for some reasons which are valid , most devs/engineers advise against using the localstorage as it prones one to xss attacks..
So I decided to implement the httponly cookie method, but I haven't seen a practical use of this done on Django, I've seen theories on implementing all these but haven't seen someone done this..
Please how can I use the httponly cookie with my token stored as a cookie with DJANGO
EDIT
I know a httponly cookie does not allow JavaScript to access a cookie, so I decided to do this.
Django sends the cookie httponly with the token as the cookie
User makes a request to the backend
server gets the token from the cookie sent as a request from the backend.
4)"where the problem now comes" I can't set the token as an header in Django, I tried using the request.headers['Autho...] = Token ....
But that doesn't allow item assignment..
So if my logic is correct this is where I'm stucked
EDIT So this time, I am now able to add a header from the server , using request.META to pass an Authorization key with the Token .... Value, that seems to work fine instead of having to use request.headers for passing an assignment..
But something happened which shocked me, in as much as I'm able to change or add an authorization token from the server , the view still gives me an error, much like I never passed a token at all.....
It's like after the whole efforts and everything nothing still changes, except if it's requested from the client side 😢.
Guess I will have to stick with localstorage for now, but still research more or wait for answers .
I've done the Authentication with token using httponly cookie..
I recalled when I asked questions and some loving guys from here helped tho, we couldn't see a straight off answer as we had to research and think as well...
The steps I used was this.
Django takes in user credentials
Django authenticate that credentials
a token is exchanged for that data
we set the token to a cookie using
set_cookie(.... , httponly=True)
** Then it was now time for the real workout .
I created a middleware which will be responsible for setting the token to an Authorization key in header dict.. instead of allowing the client to do this.
---- The client couldn't handle this coz it was now a httponly flag which will prevent js from accessing it as the purpose of using httponly was for this to prevent xss attacks when tokens/cookies are normally stored in a browser storage
we then handle the middleware to our taste, as in mine I tried making sure it work for only some views and not all views (will be planning on making a custom decorator for it)
then last was to 🤔🤔 we'll have fun and smile at seeing me create something as such without a previous tutorial...
The GitHub repo link https://github.com/HarryAustin/tweeter-DrfTest-httonlycookie

Django DRF with React: How to obtain CSRF cookie?

I have a React frontend running at frontend.example.com and a Django backend with DRF running at backend.example.com. I am using Django Session Authentication and I want to properly implement CSRF protection.
Taking the React login page frontend.example.com/login as an example. It's the first time for a user to visit the page. There is a form with a user and password and on submit a new POST request is created to the Django backend. To the best of my knowledge, the CSRF token cookie should already be included in this request, right?
How to obtain that CSRF token from the Django backend? I am thinking of doing a GET request to the Django backend on loading the login-page to obtain that CSRF token cookie. Is that the way to do it or is there any other best practice?
Django has a section for AJAX request and how to handle CSRF: AJAX
Using this method you should send the token over and over again for each post request. The other method is using CORS. in this method, you only respond to the domains that you already whitelisted with headers that are whitelisted as well. So, instead of getting and passing CSRF token, you check if the request is coming from the right domain and then you can respond to it. And combining with a token system for user authentication, you should be good.
You can use this package for handling CORS if you use DRF: django-cors-headers
Using rate limiting can also help you avoid spams and robots to do noticeable harm.

How do I send csrftoken from Django Rest Framework backend to React Native front-end?

I am building an application after finishing up my website. Now, the backend for both of these should be common, but Django's csrf token is meant to be a security against this. Since I am not using a web browser, I am unable to get a csrf token cookie. At the same time, django will need it to access its APIs.
Is there any way I can get the cookie from Django and get it into React Native?
Not clear what you want to do. But if you are writing a native application, why don't you use a token identification mechanism?
There are lots of simple (and less simple solutions out there).
Assuming you are using django rest framework.
Simple built-in Token authentication
https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
Token, but with expiry and DB encryption
https://github.com/James1345/django-rest-knox
JWT
https://github.com/davesque/django-rest-framework-simplejwt
May I know your login URL? Use rest-auth login URL. Allauth URL gives Csrf issue.

Django and CSRF protection for mobile apps

I am using Django + Django REST Framework + Django OAuth Toolkit.
I understand that AJAX calls from a web session require CSRF protection, but it is my understanding that mobile apps don’t as the very thing CSRF check are protecting against can’t happen in a dedicated app. If a person has an OAuth token, they are not using our web app so it seems I don’t need to perform CSRF checks in that case.
Is there any way to disable CSRF checks on REST Framework endpoints when a request includes an OAuth token, and if so is this a safe thing to do? Or should all requests be protected by the CSRF mechanism regardless?
You should probably be using DRF's token authentication with a mobile app. Initially, the user logs in to your backend with a username and password and then the backend issues a token for that instance of the mobile app, which [securely] stores the token locally. With token authentication and the reality of sending your credentials (over SSL/HTTPS) to the server on every request, you obviate the need for a CSRF check and thus no CSRF check is done.