score:-1
i've got this problem once, i was using token authentication. that's how i solved it. but not sure if it is the best idea. i only used csrf_exempt for this view and all others views are viewsets.
@csrf_exempt
def get_current_user(request, *args, **kwargs):
if request.method == 'get':
user = request.user
serializer = userdataserializer(user)
return jsonresponse(serializer.data, safe=false)
my middleware in settings.py
middleware = [
'django.middleware.security.securitymiddleware',
'django.contrib.sessions.middleware.sessionmiddleware',
'corsheaders.middleware.corsmiddleware',
# 'django.contrib.auth.middleware.sessionauthenticationmiddleware',
'django.middleware.common.commonmiddleware',
'django.middleware.csrf.csrfviewmiddleware',
'django.contrib.auth.middleware.authenticationmiddleware',
'django.middleware.locale.localemiddleware',
'oauth2_provider.middleware.oauth2tokenmiddleware',
'django.contrib.messages.middleware.messagemiddleware',
'django.middleware.clickjacking.xframeoptionsmiddleware',
'auditlog.middleware.auditlogmiddleware',
]
score:0
to make csrf protection work you will need csrf cookie sent from django to react as a response to some request (like login or sth else). it will set cookie using set-cookie on frontend side. so make sure that you have a view that does that on django side. if not, create a view that as response generates that token.
how django (4.04) csrf validation work (simplified, based on middleware/csrf.py):
gets csrf token from cookie (so frontend needs to resend it back on another request) - it might also get it from session but in case of react i would not use it
def _get_token(self, request): .... try: cookie_token = request.cookies[settings.csrf_cookie_name] except keyerror: return none
compares that cookie csrf token with non-cookie token from request:
def _check_token(self, request): # access csrf_token via self._get_token() as rotate_token() may have # been called by an authentication middleware during the # process_request() phase. try: csrf_token = self._get_token(request) except invalidtokenformat as exc: raise rejectrequest(f"csrf cookie {exc.reason}.") if csrf_token is none: # no csrf cookie. for post requests, we insist on a csrf cookie, # and in this way we can avoid all csrf attacks, including login # csrf. raise rejectrequest(reason_no_csrf_cookie) # check non-cookie token for match. request_csrf_token = "" if request.method == "post": try: request_csrf_token = request.post.get("csrfmiddlewaretoken", "") except unreadableposterror: # handle a broken connection before we've completed reading the # post data. process_view shouldn't raise any exceptions, so # we'll ignore and serve the user a 403 (assuming they're still # listening, which they probably aren't because of the error). pass if request_csrf_token == "": # fall back to x-csrftoken, to make things easier for ajax, and # possible for put/delete. try: request_csrf_token = request.meta[settings.csrf_header_name] except keyerror: raise rejectrequest(reason_csrf_token_missing) token_source = settings.csrf_header_name else: token_source = "post" try: request_csrf_token = _sanitize_token(request_csrf_token) except invalidtokenformat as exc: reason = self._bad_token_message(exc.reason, token_source) raise rejectrequest(reason) if not _does_token_match(request_csrf_token, csrf_token): reason = self._bad_token_message("incorrect", token_source) raise rejectrequest(reason)
as you can see you either need to include csrfmiddlewaretoken
in post request or include it in header with key: settings.csrf_header_name
and value read from cookies on front-end side.
so for example you set withcredentials: true
(to include initial cookie), read that initial csrf cookie in react and add to header in axios request at specific key.
when in question, i would just debug request setting up breakpoints in this code of django in middleware/csrf.py and you can trace what is missing and why csrf validation fails.
Source: stackoverflow.com
Related Query
- Django (DRF) & React - Forbidden (CSRF cookie not set)
- Django REST and React - JWT Cookie not getting set in browser but working with postman
- Django and React: csrf cookie is not being set in request header
- Express Session Cookie Not Being Set when using React Axios POST Request
- How to send CSRF Cookie from React to Django Rest Framework with Axios
- Forbidden (CSRF cookie not set.) with React and axios
- React App + Spring Boot - JWT auth token inside a cookie is not set in Chrome
- Why is the csrf cookie set when sending POST request to localhost:8000, but not when sending POST request 127.0.0.1:8000?
- Why DRF shows Forbidden (CSRF cookie not set.) without @api_view(['POST'])?
- React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH
- Nodejs won't set cookie for React CRA application even with proxy
- Cookie not being set in browser
- using apollo, cookie in response header but not being set
- Assets destination folder is not set Skipping react native (Images not loading in the APK)
- Django - DRF (django-rest-framework-social-oauth2) and React creating a user
- Deploying Seprate React Frontend and Django DRF API
- How to set cookie in React Native with Expo?
- React event.target is not the element I set event Listener on
- Cookie in Set-Cookie header not being set
- webpack not reflecting changes in js files with react and django
- How to debug react in vs code ? Error break point set but not yet bound
- React Cookie + ReactJS: How to set expiration time for a cookie?
- React setState does not set state during a while loop
- How to get CSRF from django in a separate React App
- React Django REST framework session is not persisting/working
- Google Optimize not working with React App (no cookie set)
- Why does React say not to set 'selected' property on <option> elements?
- Django React CSRF Issues
- Django backend, React frontend and CSRF Post
- React Custom Hook set function returned is not a function
More Query from same tag
- Unable to capture onClick events on Marker's children included in deck.gl@^7.1.10
- Having styling issue
- How do I recover the reset password token from Supabase in React?
- JavaScript map inside map
- Redux-Loop dispatch not returning promise from reducer
- function not return value from request
- React Big Calendar shows only certain range of time
- How to deleting Entries from Reducer / how to return a new state? (React / Redux)
- Why useContext does't work in my function?
- I have array data in console how can i display it in react js?
- Gatsby and Classnames library: Apply CSS class depending on content of div
- How do I controll return type of useState
- How to override env variables in React JS application with Kuberenetes?
- cannot load png files with webpack, unexpected character
- React change only clicked button text [Looped]
- Use react routes depending by condition
- Access ref of component in another component?
- React triggering navigation from nested components
- Why NextJS using Docker container did not reload after changed code for dev environment?
- Can't make react router work with multi-layer routes with parameters
- Why do I get an array of promises when getting data from the blockchain with useEffect?
- What is dispatcherIndex used for in React TODO example
- How to organize partial entities in normalized redux store?
- How to make relative margin in flex-item in css?
- React won't update state after using useState hook update function
- Typescript error 2769 - Trying to pass a process information to data state to use it on a modal
- GraphQL Apollo Query client: Poll interval not working with TypeScript
- Best way to request unknown number of API pages in useEffect hook
- how to reveal/unrveal password inside input in Data Driven Forms (it npm react package)?
- How to hide the header from Tab navigation (bottom-tabs) in react navigation 5.x?