Django Framework 6-MiddleWare

1. What is Django middleware?

(1) Middleware is Django's hook framework for processing requests/responses.This is a light, low-level "plug-in" system for changing Django and client inputs and outputs globally.

2. As I understand, add an ornament to Django. When a client sends a request to Django, it is up to the middleware to process it before deciding whether to hand it over to Views

3. What tasks are generally handled?Logging of requests, user login authentication, request address jump, IP address filtering, etc.


2. Where is the middleware set up?

Under project, under project packageSettings.pyFile, MIDDLEWARE list, add or delete list items.


3. How do multiple middleware work?

The list of middleware runs from front to back, stops with errors and returns data from back to front.LIFO like list.


4. When does the middleware run in one request?

1. Initialization between middleware when Django service starts

2. Call between middleware when client requests


5. How do I make a middleware myself?

1. Create a new oneXxxxxx.pyThe python file can be placed anywhere in the Projects, for example, when I create a new one hereMidtest.pySave to project root directory.

2. InMidtest.pyCreate a middleware function or class in

from django.utils.deprecation import MiddlewareMixin
#Import Middleware Class

class MyMiddleware(MiddlewareMixin):
    #Custom Class Inherits Middleware Class
    def process_request(self,request):
    #Override Middleware Method
        print("---process_request---")

3. Add the created MIDDLEWARE toSettings.pyMIDDLEWARE List

MIDDLEWARE=["midtest.MYMiddleware",
           ]


6. Middleware Advancement:


1. Five methods of customizing middleware and execution sequence:

process_request(): execute when the client requests, then requestUrls.py

Process_View():Urls.pyAfter that,Views.pybefore

Process_Template_Response ():Views.pyafter

process_exception(): captureViews.pyError, so inViews.pyafter

process_response(): Run after exception

2. Code Instances

from django.utils.deprecation import MiddlewareMixin
class MyMiddleware(MiddlewareMixin):
    #All methods are listed in the example, but only one can be used
    #Of course, you can also use class MyMid: uInit_uAnd uCall_uTo override, refer to the writing of the inherited MedelwareMixin class
    
    def process_request(self, request):
    #Request parameter, client request
    #Functions such as authenticated login, IP block list can be set
    
        #1. --- Log on through session validation-----
        if request.path_info == '/login/':    #Request login to execute normally
            return
        elif not request.session.get('k1', None): #Request other pages to judge not logged in jump to login
            return redirect('/login/')
    
        #2. -- - - Set client IP for denial of access -- - ---
        refuse_ip=["172.0.0.1"]
        if request.META.get('HTTP_X_FORWARDED_FOR', None):    #'HTTP_X_FORWARDED_When using reverse proxy, look for the user's true IP
            ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            ip = request.META['REMOTE_ADDR']                  #If'HTTP_X_FORWARDED_Get REMOTE_if FOR'does not existADDR
        
        if ip in refuse_ip:                                   #Determine if IP is in the Deny List
            return HttpResponse("What's wrong with you? You won't be landed!")
        
    
    def process_view(self, response, view_func, *args, **kwargs):
        #request Client request
        #view_func's requested view function
        #* args,**kwargs] parameters included with the request
        
        
    def process_exception(self, request, response):
        #IfViews.pyFunction error, execution
        #request Client request

    

7. CSRF Middleware


Cross-site request forgery, also known as one-click attack or session riding, is often abbreviated as CSRF or XSRF and is a *** method to coerce users from performing unintentional operations on currently logged-in Web applications.Compared with Cross-Site Scripting (XSS), XSS leverages the user's trust in a specified site, and CSRF leverages the site's trust in a user's web browser.

    

Solutions:

1. Check the Referer field of HTTP

2. Add Check Token

    

CSRF checks for Django:

1. django uses Token with checks added.

2. Method 1: Using middleware'django.middleware.csrf.CsrfViewMiddleware'

Method 2: The server sends an encrypted Token to the client for client authentication

3. Add tag {% csrf_to HTML From Token%}

4. CSRF source:

class CsrfViewMiddleware(MiddlewareMixin):
    def _accept(self, request):
        request.csrf_processing_done = True
        return None
    def _reject(self, request, reason):
        logger.warning(
            'Forbidden (%s): %s', reason, request.path,
            extra={
                'status_code': 403,
                'request': request,
            }
        )
        return _get_failure_view()(request, reason=reason)
    def _get_token(self, request):
        if settings.CSRF_USE_SESSIONS:
            try:
                return request.session.get(CSRF_SESSION_KEY)
            except AttributeError:
                raise ImproperlyConfigured(
                    'CSRF_USE_SESSIONS is enabled, but request.session is not '
                    'set. SessionMiddleware must appear before CsrfViewMiddleware '
                    'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '')
                )
        else:
            try:
                cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                return None
            csrf_token = _sanitize_token(cookie_token)
            if csrf_token != cookie_token:
                # Cookie token needed to be replaced;
                # the cookie needs to be reset.
                request.csrf_cookie_needs_reset = True
            return csrf_token
    def _set_token(self, request, response):
        if settings.CSRF_USE_SESSIONS:
            request.session[CSRF_SESSION_KEY] = request.META['CSRF_COOKIE']
        else:
            response.set_cookie(
                settings.CSRF_COOKIE_NAME,
                request.META['CSRF_COOKIE'],
                max_age=settings.CSRF_COOKIE_AGE,
                domain=settings.CSRF_COOKIE_DOMAIN,
                path=settings.CSRF_COOKIE_PATH,
                secure=settings.CSRF_COOKIE_SECURE,
                httponly=settings.CSRF_COOKIE_HTTPONLY,
            )
            patch_vary_headers(response, ('Cookie',))
    def process_request(self, request):
        csrf_token = self._get_token(request)
        if csrf_token is not None:
            # Use same token next time.
            request.META['CSRF_COOKIE'] = csrf_token
    def process_view(self, request, callback, callback_args, callback_kwargs):
        if getattr(request, 'csrf_processing_done', False):
            return None
        if getattr(callback, 'csrf_exempt', False):
            return None
        if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
            if getattr(request, '_dont_enforce_csrf_checks', False):
                return self._accept(request)
            if request.is_secure():
                referer = force_text(
                    request.META.get('HTTP_REFERER'),
                    strings_only=True,
                    errors='replace'
                )
                if referer is None:
                    return self._reject(request, REASON_NO_REFERER)
                referer = urlparse(referer)
                if '' in (referer.scheme, referer.netloc):
                    return self._reject(request, REASON_MALFORMED_REFERER)
                if referer.scheme != 'https':
                    return self._reject(request, REASON_INSECURE_REFERER)
                good_referer = (
                    settings.SESSION_COOKIE_DOMAIN
                    if settings.CSRF_USE_SESSIONS
                    else settings.CSRF_COOKIE_DOMAIN
                )
                if good_referer is not None:
                    server_port = request.get_port()
                    if server_port not in ('443', '80'):
                        good_referer = '%s:%s' % (good_referer, server_port)
                else:
                    good_referer = request.get_host()
                good_hosts = list(settings.CSRF_TRUSTED_ORIGINS)
                good_hosts.append(good_referer)
                if not any(is_same_domain(referer.netloc, host) for host in good_hosts):
                    reason = REASON_BAD_REFERER % referer.geturl()
                    return self._reject(request, reason)
            csrf_token = request.META.get('CSRF_COOKIE')
            if csrf_token is None:
                return self._reject(request, REASON_NO_CSRF_COOKIE)
            request_csrf_token = ""
            if request.method == "POST":
                try:
                    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
                except IOError:
                    pass
            if request_csrf_token == "":
                request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')
            request_csrf_token = _sanitize_token(request_csrf_token)
            if not _compare_salted_tokens(request_csrf_token, csrf_token):
                return self._reject(request, REASON_BAD_TOKEN)
        return self._accept(request)
    def process_response(self, request, response):
        if not getattr(request, 'csrf_cookie_needs_reset', False):
            if getattr(response, 'csrf_cookie_set', False):
                return response
        if not request.META.get("CSRF_COOKIE_USED", False):
            return response
        self._set_token(request, response)
        response.csrf_cookie_set = True
        return response





Tags: Python Django Session

Posted on Mon, 25 May 2020 12:53:24 -0400 by siropchik