English 中文(简体)
React & Django - WARNING:django.request: 隐蔽: /api/user - SessionAuthentication
原标题:React & Django - WARNING:django.request:Forbidden: /api/user - SessionAuthentication
The bounty expires in 6 days. Answers to this question are eligible for a +100 reputation bounty. Axil is looking for a canonical answer:
Would like to setup correctly the SessionAuthentication to work on Docker, Django, React.

I ved Creat this Django & React Project ( https://github.com/axilaris/docker-django-react-celery-redis); I m在接触Authentication方面的困难。 你们可以很容易地测试和脱离我的法典:

  • docker-compose build
  • docker-compose up

我在进入用户/用户时不断获得准入问题(可以登记、登录)

backend_container   | Forbidden: /api/user
backend_container   | WARNING:django.request:Forbidden: /api/user

You can look more the logs here: https://gist.github.com/axilaris/7b7a5c50f4f7112b440eaf8ef8100d9d In my django api code (backend/user_api/views.py):

        class UserView(APIView):
            permission_classes = (permissions.IsAuthenticated,)
            authentication_classes = (SessionAuthentication,)
            def get(self, request):
                serializer = UserSerializer(request.user)
                return Response({ user : serializer.data}, status=status.HTTP_200_OK)
    
    
    
    In settings.py:
    
    CORS_ALLOWED_ORIGINS = [
         http://localhost ,
         http://127.0.0.1 ,
         http://0.0.0.0 ,
    ]
    
    CORS_ALLOW_CREDENTIALS = True
    
    INSTALLED_APPS = [
    ..
         corsheaders ,
    ]
    
    
    MIDDLEWARE = [
         corsheaders.middleware.CorsMiddleware ,
    ...
    ]
    

反应:

    axios.defaults.xsrfCookieName =  csrftoken ;
    axios.defaults.xsrfHeaderName =  X-CSRFToken ;
    axios.defaults.withCredentials = true;
    
      useEffect(() => {
        client.get("/api/user")
        .then(function(res) {
          setCurrentUser(true);
        })
        .catch(function(error) {
          setCurrentUser(false);
        });
      }, []);

这里是我的网络标志:https://gist.github.com/axilaris/f5076f8a1e009d77df78de562259427e

/api/login确实提供了 c和 session。 但是,这一 co子在(api/user)中没有使用。

因此,每当Ilogin和I在浏览器上重载回当地东道方之后,它就禁止(api/user)进入日志。 我感到,索马里再次解放联盟的成立是正确的,其全权证书在背后和前身都是真实的。

UPDATE from ChatGPT (questing how to make it work when with HttpOnly):

If you can t access the session cookie from the client-side, it s probably because the cookie has the HttpOnly flag set. This is a security feature that prevents JavaScript from accessing the cookie, helping mitigate cross-site scripting attacks.
问题回答

你:

Client (React) --> [HTTP Request with CSRF Token] --> Django Backend
                                                  /
                                                  |
                                                  +--- [Session Authentication & CSRF Validation]

SessionAuthentication to work, ensures Django s session cookie (sessionid/code>) and CSRF token cookie (csrftoken/code> www.un.org/chinese/sc/presidency.asp http://www.reddit.com/r/django/comments/zwsaf2/how_to_use_ only_cookied_for_drf/"rel=“nofollow noretinger”>。

自会议以来(sessionid) 改性应用不应与它直接互动。 相反,确保<条码>轴心/条码>组合正确地包括所有请求的全权证书。 这一部分似乎在您的设置中进行了正确的配置(axios.defaults.withCredentials set to true)。

<代码>制定。 应包括:

SESSION_COOKIE_HTTPONLY = True  # Default value is True, which is recommended
SESSION_COOKIE_SAMESITE =  Lax  # Consider  None  if strictly necessary and secure is set
SESSION_COOKIE_SECURE = True    # Set to True if you are using HTTPS

关于CSRF表:

CSRF_COOKIE_HTTPONLY = False    # Should generally be False to allow JavaScript to read the value
CSRF_COOKIE_SECURE = True       # Set to True if you are using HTTPS

设置<条码>CSRF_COOKIE_HTTPONLYFalse将使你的申请更容易受到特别安全局的攻击,因为它使 Java本能够进入CSRF表。 一种更好的做法是将CSRF保留到HttpOnly上,并从一个单独的APIC端点获得,目的是明确恢复CSRF,或者将CSRF添加到你的网页上,并将 Java读成。

Although... as documented since 2016 in django/django PR 7700 and commit c27104a

指定CSRFCookie为 HttpOnly don t 提供任何实际保护,因为CSRF只是为了保护不受交叉攻击。 如果攻击者可以通过Juane读书,他们就象浏览器知道的那样,已经回到同一个领域,因此他们可以做任何事情。 (XSS是比CSRF大得多的漏洞。)

在使南方市场能够进入时考虑的主要风险是:XSS—— 交叉网址:。 如果你的申请容易受特别安全局的管辖,攻击者可充分利用这一手段,完全绕过欧洲安全局的保护。 因此,在做出任何让南方市场暴露于 Java本的决定的同时,还应制定严格的科学、技术和物质缓解战略。 例如,见Django XSS: 范例和预防,StackHawk

• 测试获取通用报告格式的流入量,并在日志上做成像。 核实React随后提出的申请包括自动在头脑中标出的CSRF,以及自动在座标(尽管 Java不能读到sessionid)。 页: 1 HttpOnlycode。





相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签