django中间件CSRF

Setup

在前后端分离的项目中,经常会遇到csrf forbidden这种情况。这时候需要在settings.py中添加一些配置。


CSRF_TRUSTED_ORIGINS = ["*"]
CSRF_COOKIE_NAME = 'csrfToken'
CSRF_COOKIE_SECURE = True 
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE=None

...

MIDDLEWARE = [
  	...
    "django.middleware.csrf.CsrfViewMiddleware",
    ...
]

Problem

Origin checking failed: 这个问题需要将前端的ip:port添加到后台的设置中。

# settings.py
CSRF_TRUSTED_ORIGINS = ["http://localhost:3011"]

CSRF cookie not set: 这个问题意味着我们并没有在cookie中设置csrf。

如果使用django template,可以在表单中添加{% csrf_token %}即可。
如果使用react,需要从后端获取token,将token放入cookie中,请求后端。

from django.middleware.csrf import get_token

...

def csrf_token_view(request):
    if request.method == 'GET':
        csrf_token = get_token(request)
        return JsonResponse({
    
    'csrfToken': csrf_token})
    else:
        return JsonResponse({
    
    'error': 'Invalid request method'}, status=400)
 path('api/v1/get-csrf-token/', csrf_token_view, name='get_csrf_token'), 

前端对应的函数,以react 为例:

  const [csrfToken, setCsrfToken] = useState('');
  const fetchToken = async () => {
    
    
    const response = await axios.get('http://35.78.130.77:11313/client/api/v1/get-csrf-token/'); // Replace with your backend API endpoint
    console.log("response is", response)
    setCsrfToken(response.data.csrfToken)
  };

  useEffect(() => {
    
    
    fetchToken();
  }, [])

...
const PostWithToken = () => {
    
    

	...
      try {
    
    
        const reqUrl = <YOURURL>;
        const response = await fetch(reqUrl, {
    
    
          method: 'POST',
          headers: {
    
    
            'Content-Type': 'application/json',
		  },
          
          credentials: 'include',  // this makes sure the request carry cookies
          body: JSON.stringify(<YourValue>),
        },
        );

在这种情况下,如果前后端的ip是一样的,就可以完成了。

No request cookies were sent: 如果前后端的域名不同,就会出现这个问题。归根结底,后端生成的cookie是有域名信息的,在前端进行post的时候,这些带域名信息的cookie会被过滤。。。。

猜你喜欢

转载自blog.csdn.net/majiayu000/article/details/131232179