Django framework CBV decorator middleware auth module CSRF cross site request problem

  • 2021-11-24 02:01:08
  • OfStack

CBV Adding Decorator

There are three ways to add decorators to CBV, all of which require importing modules:


from django.utils.decorators import method_decorator

The first one is added directly to the method:


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')

The second is to add:


from django.utils.decorators import method_decorator

@method_decorator(auth, name='get')  #  Method name 
class MyLogin(View):
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')

The third is to override the dispatch method in as_view (), which adds all the methods in the class after adding the decorator.


from django.utils.decorators import method_decorator


class MyLogin(View):
    @method_decorator(auth)
    def dispatch(self, request, *args, **kwargs):
        super.__init__()
    def get(self, request):
        return HttpResponse('Is from get')

    def post(self, request):
        return HttpResponse('Is from post')

Django middleware

Introduction

Django has seven middleware by default:


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',
]

In the process of browser from request to response, Django needs to be processed by these seven middleware, all of which inherit MiddlewareMixin by default.

Django enables programmers to customize middleware and exposes 5 customizable methods for programmers.

process_request process_response process_view process_template_response process_exception

How to customize middleware

1. Create a folder with any name in the project name or application name (there is a prompt for creating the path under the application, but there is no prompt for creating under the project)

2. Create an py file with any name in this folder

3. Write the class within the py file (the class must inherit from MiddlewareMixin)


from django.utils.deprecation import MiddlewareMixin

Then you can customize 5 methods in this class

(Not all of these five need to be written, write several with several)

4. The path of the class needs to be registered in the configuration file as a string to take effect (that is, in MIDDLEWARE in setting. py)

process_request

When the request comes over, it needs to go through the process_request method in every middleware. The result sequence is executed from top to bottom according to the middleware registered in the configuration file. If the middleware does not define the process_request method, execution of the middleware is skipped directly. If the method returns an HttpResponse object, the request will not continue to be executed later but will be returned directly (check failure does not allow access). The process_request method is used to do all the restriction functions of global relevance

process_response

The response goes through the process_response method in every middleware. This method has two additional parameters, request and response. This method must return 1 HttpResponse object

The default return parameter response can also be customized to return HttpResponse

The order is executed from bottom to top according to the middleware registered in the configuration file.

If there is no definition, skip the execution directly.

process_view

This method in middleware is automatically executed from top to bottom before executing the view function after successful route matching

process_template_response

Triggered when the returned HttpResponse object has an render attribute

process_exception

Triggered when an exception occurs in the view function

csrf cross-site request forgery

Because the CSRF attack is aimed at the browser can not tell whether the request is the real user himself, the key to prevent it is to put information that hackers can't forge in the request. So as to prevent hackers from forging a complete request to deceive the server.

Django uses token authentication to prevent CSRF.

CSRF is a stand-alone component in Django. MIDDLEWARE comments it out and it no longer executes.

If you want to submit an post request that passes csrf validation, you need to add a validation string to the from form on the html page.

csrf Validate form Form


<form action="" method="post">
    {% csrf_token %}
    <input type="text" placeholder=" User name ">
    <input type="password" placeholder=" Password ">
    <input type="submit">
</form>

Ajax csrf Authentication


<script>
    $('.btn').click(function (){
        $.ajax({

            url:'',
            type:'post',
            //  No. 1 1 A kind of way 
            // data:{'username':'jesse', 'csrfmiddlewaretoken':$('[name="csrfmiddlewaretoken"]')},
            //  No. 1 2 Species 
            data:{'username':'jesse', 'csrfmiddlewaretoken':'{{ csrf_token }}'},
            success:function(){

            }
        })
    })
</script>

Decorator for CSRF cross-site requests

The csrf middleware verifies that all methods are validated, but we will encounter all methods that are validated, but a few functions that are not validated. At this time, decorators will be used.

Need to verify the addition of this decorator:


@csrf_protect

Add this decorator without verification:


@csrf_exempt

#  If the function has a returned html You can't add any more {% csrf_token %}

csrf_protect decorator can also be added to CBV, and CBV to add decorator usage 1.

The csrf_exempt decorator can only be added by overwriting the dispatch method.

Django Auth Component

Django User Authentication Component Class 1 is used in user login registration to judge whether the current user is legal. To call this component, auth module needs to be imported, and the authentication function of auth depends on auth_user table.

First, create a super user, so that you can log in to the background of Djangoadmin. Click Run manage. py Task in the tools menu above pycharm, and enter the command (first, you must have auth_user table in the library to create it)


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')
0

To use the auth module that needs to be imported:


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')
1

auth Module Actual Use (Authenticate User, Set session)


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')
2

In addition to authenticating the user and setting session, the auth module can also set the authentication decorator.


from django.contrib.auth.decorators import login_required


#  The same use auth The self-contained decorator also needs to be imported login_required

@login_required(login_url='/login/')
#  When the decorator is used, it needs to be transmitted   No login   The returned route does not pass the address that comes with the default access account/login 
def func(request):
    return HttpResponse('FUNC PAGE')

Change password


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')
4

Logout function


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')
5

Register and put into storage


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')
6

Extension of auth_user Table

The fields of auth_user table are created by the system for us, and it is inevitable that the fields cannot meet our needs in the process of using them. How can we extend the table in this case?

Extending the auth_user table needs to be done in models. py. First, we need to import a module:


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')
7

Adding fields requires inheriting AbstractUser


class UserInfo(AbstractUser):
  phone = models.CharField(max_lenth=32)
  addr = models.CharFiled(max_lenth=32)
  #  Add a field 

You must write 1 configuration in settings. py after adding fields


from django.utils.decorators import method_decorator


class MyLogin(View):
	@method_decorator(auth)
	def get(self, request):
    return HttpResponse('Is from get')

	def post(self, request):
    return HttpResponse('Is from post')
9

It should be noted that once the extension class executes the migration command, it can no longer be extended


Related articles: