简体   繁体   English

Django 和 React:请求标头中未设置 csrf cookie

[英]Django and React: csrf cookie is not being set in request header

To explain my situation, if I logged in from backend, csrf cookie is set in cookie tab, the problem occur in frontend, if i try to login from there, csrf cookie is not in request header (being undefined), some code provided:为了解释我的情况,如果我从后端登录,csrf cookie 设置在 cookie 选项卡中,问题发生在前端,如果我尝试从那里登录,csrf cookie 不在请求标头中(未定义),提供了一些代码:

settings.py:设置.py:

ALLOWED_HOSTS = ['*']
ACCESS_CONTROL_ALLOW_ORIGIN = '*'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_METHODS = '*'
ACCESS_CONTROL_ALLOW_HEADERS = '*'

'''
SESSION_COOKIE_SECURE = True
'''
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'


CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000",'http://127.0.0.1:8000','http://localhost:3000']

setting SAMESITE protocol to anything else haven't made any change将 SAMESITE 协议设置为其他任何内容均未进行任何更改

in views.py, we have login view (class based):在 views.py 中,我们有登录视图(基于类):

class LoginView(views.APIView):
    permission_classes = [AllowAny,]
    serializer_class = serializer.LoginSerializer
    def post(self,request):
        data = serializer.LoginSerializer(data=request.data)
        print(data.is_valid())
        if data.is_valid():
            email = data.data['email']
            password = data.data['password']
            auth = authenticate(username=email,password=password)
            if auth:
                login(request,auth)
                return HttpResponse("Success",status=200)
            else:
                print(password == "")
                if email == "" and password =="":
                    return HttpResponse('Both email and password field are empty',status=400)

                elif email == "":
                    return HttpResponse('Email field is empty',status=400)
                elif password == "":
                    return HttpResponse('Passowrd field is empty',status = 400)
        else:
            return HttpResponse("Both email and password fields are empty",status=400)

in serializer.py, we got the login serializer:在 serializer.py 中,我们得到了登录序列化器:

class LoginSerializer(serializers.Serializer):
    email = serializers.CharField(required=False)
    password = serializers.CharField(required=False,allow_null=True,allow_blank=True)

in react (frontend side), here is how i am making a post request:在反应(前端)中,这是我发出帖子请求的方式:

function Login(){
    const [login,setLogin] = useState({'email':'','password':''})
    const {email,password} = login
    const navigate = useNavigate()

    let handleChange = (e)=>{
        setLogin(
            {
                ...login,
                [e.target.name]:e.target.value
            }
        )

    }

    
    let handleSubmit = (e)=>{
        e.preventDefault()
        axios.post('http://127.0.0.1:8000/login/',login,{headers: {'Content-Type': 'application/json','X-CSRFToken':Cookies.get('csrftoken')}}).then(
            (res)=>{

 
                    console.log(res)
                    console.log(Cookies.get('csrftoken')) //undefined here

            }
        ).catch((e)=>{
    console.log(e)
            }
        })

    }
}

this is part of the code btw ^.这是代码的一部分顺便说一句^。

edit: I have a csrf view too, not sure how to use it:编辑:我也有一个 csrf 视图,不知道如何使用它:

class GetCSRFToken(views.APIView):
    permission_classes = [AllowAny, ]

    def get(self, request, format=None):
        return Response({ 'success': 'CSRF cookie set' })

any help is welcomed.欢迎任何帮助。

I suggest to you that try to work with your both servers using HTTPS.我建议您尝试使用 HTTPS 与您的两台服务器一起工作。 Some help: Django一些帮助:Django

To ReactJS simply use the same certificates generated to use in Django to tun the server with next command:对于 ReactJS,只需使用生成的相同证书以在 Django 中使用来使用下一个命令调整服务器:

HTTPS=true SSL_CRT_FILE=path/server.crt SSL_KEY_FILE=path/server.key npm start

This with the goal of change your settings:这是为了更改您的设置:

CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SAMESITE = 'Strict'  
CSRF_COOKIE_SECURE = True
CSRF_TRUSTED_ORIGINS = [ "https://127.0.0.1:3000", ...] 

But is not totally necessary.但也不是完全必要的。

Now, your view GetCSRFToken is incorrect because return a message.现在,您的视图GetCSRFToken不正确,因为返回了一条消息。 This an example that I have implemented.这是我实施的一个例子。 The key is the decorator ensure_csrf_cookie关键是装饰器ensure_csrf_cookie

Views.py:视图.py:

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie

class CsrfTokenView(APIView):
"""Send to the login interface the token CSRF as a cookie."""

    @method_decorator(ensure_csrf_cookie)
    def get(self, request, *args, **kwargs) -> Response:
        """Return a empty response with the token CSRF.

        Returns
        -------
        Response
            The response with the token CSRF as a cookie.
        """
        return Response(status=status.HTTP_204_NO_CONTENT)

In ReactJS just code a useEffect with empty dependencies to do the request just after mount the component.在 ReactJS 中,只需编写一个带有空依赖项的useEffect即可在安装组件后执行请求。

useEffect(() => {
    axios.get('/url/csrf-token/', {
            headers: { 'Authorization': null },
            withCredentials: true,
        }
    ).catch( () => {
        alert('Error message.');
    });
}, []);

At this point, you will be able to watch the cookie in 'developer tools'.此时,您将能够在“开发者工具”中查看 cookie。 Finally, in your LoginView add the csrf_protect decorator to your post method to make sure the endpoint needs the CSRF_TOKEN.最后,在您的 LoginView 中将csrf_protect装饰器添加到您的post方法中,以确保端点需要 CSRF_TOKEN。

Views.py:视图.py:

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
...

class LoginView(views.APIView):
    ...
    @method_decorator(csrf_protect)
    def post(self,request):
        # code

Don't forget map the url of the csrf view and put the correct in the request ( useEffect ).不要忘记映射 csrf 视图的 url 并将正确的放在请求中( useEffect )。

Also in your request of login, add withCredentials: true .同样在您的登录请求中,添加withCredentials: true This way the request sent the cookies (CSRF).通过这种方式,请求发送了 cookie (CSRF)。 Django is going to compare the header X-CSRFToken with the value of the cookie received and if match, it is going to execute the method body. Django 会将标头X-CSRFToken与接收到的 cookie 的值进行比较,如果匹配,它将执行方法体。

I think that's it.我想就是这样。 Let me know if it works.让我知道它是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM