django 解决csrf跨域问题

Posted Pythia丶陌乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django 解决csrf跨域问题相关的知识,希望对你有一定的参考价值。

1、中间件代码

[[email protected] mysite]# tree middlewares
middlewares
├── base.py
├── base.pyc
├── cors.py
├── cors.pyc
├── __init__.py
└── __init__.pyc

0 directories, 6 files
[[email protected]-node01 mysite]# 

2. 代码

middlewares/base.py

[[email protected] mysite]# cat middlewares/base.py
#!/bin/env python
# -*- coding: utf-8 -*-
class MiddlewareMixin(object):
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin, self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, process_request):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, process_response):
            response = self.process_response(request, response)
        return response
[[email protected]-node01 mysite]# 

核心文件middlewares/cors.py

[[email protected] mysite]# cat middlewares/cors.py
#!/bin/env python
# -*- coding: utf-8 -*-
from .base import MiddlewareMixin


class CORSMiddleware(MiddlewareMixin):
    """CORS中间件"""

    def process_response(self, request, response):
        if request.method == "OPTIONS":
            response[Access-Control-Allow-Origin] = *
            response[Access-Control-Allow-Headers] = *
            response[Access-Control-Allow-Methods] = *
        else:
            response[Access-Control-Allow-Origin] = *
        return response
[[email protected]-node01 mysite]# 

3. settings.py文件配置

MIDDLEWARE = [
    django.middleware.security.SecurityMiddleware,
    django.contrib.sessions.middleware.SessionMiddleware,
    django.middleware.common.CommonMiddleware,
    django.middleware.csrf.CsrfViewMiddleware,
    django.contrib.auth.middleware.AuthenticationMiddleware,
    django.contrib.messages.middleware.MessageMiddleware,
    django.middleware.clickjacking.XFrameOptionsMiddleware,
    mysite.middlewares.cors.CORSMiddleware
]

 

以上是关于django 解决csrf跨域问题的主要内容,如果未能解决你的问题,请参考以下文章

前后端分离,解决跨域问题及django的csrf跨站请求保护

Django跨域请求CSRF的方法示例

django使用csrf防止跨域报错

如何使用 CSRF 令牌进行跨域 Ajax 调用?

CSRF-跨域访问保护

flask的跨域问题