django middleware csrf auth certification



django middleware
can do global access frequency limitation, identity verification, blacklist, whitelist
Usage:
create a new folder, create a folder py file, write the following code
Precautions: Do you write the class must continue MiddlewareMixin
from django Import MiddlewareMixin .utils.deprecation
from django.shortcuts Import HttpResponse, the render

class MyMiddleWare (MiddlewareMixin):
DEF process_request (self, Request):
Print ( 'my first custom middleware in process_request method')
# return HttpResponse ( 'I was the first object-oriented middleware which returned')
# return the render (Request, 'index.html')
# process_request default method does not return HttpResponse objects, if you return the
# subsequent middleware would not go, but direct method is the same level do not go process_response

process_response DEF (Self, Request, Response):
Print ( 'middleware process_response Method I is a first custom')
return Response


Django allows users to customize the middleware, and exposed to the user can customize the five methods
1 .process_request: performs (must master) when a request comes
2.process_response: response will be executed (must master) return
and the need to specify what triggered when each method (must master)

3.process_view: match before routing the successful implementation of the view function, in turn process_view method
4.process_exception: view function in error, will be followed by the implementation process_exception method
5.process_template_response: process_template_response method will trigger when a view function must return the render target (to understand)



CSRF CSRF
how csrf check
< Action = form "" Method = "POST">
{%}% csrf_token
<the p-> username: <the INPUT of the type = "text" name = "username"> </ the p->
<the p-> Money: <the INPUT of the type = "text" name = "Money"> </ the p->
<the p-> other accounts: <INPUT type = "text" name = "Others"> </ P>
<INPUT type = "Submit">
</ form>
<INPUT type = "hidden" name = "csrfmiddlewaretoken" value = "HHxKItr7Z17sZxCAtybnOeV5ne5K3xnvkymENCupB5ylL8h8kWBIiklm9K10paxE">

Ajax how csrf check
# Find jQuery label acquisition by frame csrfinput key-value pair parameter data manually applied inside
$ ( 'Button') the Click (function () {.
$ .ajax ({
URL: '',
type:'post',
data:{'name':'jason','csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()},
success:function (data) {
console.log(data)
}
})
})

局部使用与局部禁用csrf
from django.views.decorators.csrf import csrf_exempt,csrf_protect

@csrf_exempt
def home(request):
return HttpResponse('home')


@csrf_protect
def login(request):
return HttpResponse('login')


auth.logout(request)
# 等价于删除session数据request.session.flush()



auth认证
# user = models.User.objects.filter(username=username,password=password).first()
user = auth.authenticate(request,username=username,password=password)
User IF:
auth.login (Request, User)
# After performing this one, view function may be obtained directly by the current user object request.user
# sentence which corresponds to the operation recording session


# is not performed when auth.login , request.user print out an anonymous user. The session table data can be deleted demonstration effect change
# request.user how to determine whether the user auth.login landing? request.user.is_authenticated

# Why after performing auth.login, other views the function can get through request.user currently logged object?
# Django middleware think there is no one called Auth what middleware, it did what events,
# can deduce what? Remove the session to check the corresponding data table inside, then put request.user, the point to look into the middleware true





"" "
# Django middleware

What is middleware?

Django request the full version of the life cycle, similar to the middleware django guard data when entering and leaving the need to go through middleware

middleware can why?

control user access frequency, global landing check, user access whitelist, blacklist

see the three default django middleware

- CSRF
- the Session
- Auth

The middleware (5 fixed method)

custom middleware

`` `Python
from django.utils.deprecation Import MiddlewareMixin


class MyMiddleWare (MiddlewareMixin):
DEF process_request (Self, Request):
Print ( 'I from the first middleware process_request defined! ')
# write a route with a view to start the project, see the printed results.
# Write a custom middleware

class MyMiddleWare (MiddlewareMixin):
DEF process_request (Self, Request):
Print ( '! I was the second custom middleware process_request')
# interpretation of middleware execution order


# in two mezzanine add process_response method. Research of Middleware messages out of order
class MyMiddleWare (MiddlewareMixin):
DEF process_request (Self, Request):
Print ( 'I was the first custom middleware process_request!')
DEF process_response (Self, Request, the Response):
print ( 'I was the first custom middleware process_response')
return the Response
# process_request come to study in direct return HttpReponse objects, how would you go next process_response

# process_view, process_exception, process_template_response
`` `

## CSRF (Cross site request forgery)

to write a simple post request, to reproduce the error message

phishing sites: bank transfer path, whether you can get, then you do exactly the same with a bank page, also submit data over the bank's excuse, when after the user enters the name of the other party and the transfer amount in the account phishing sites, click send. In fact, the interior is replaced by the other account account fraud personnel of phishing sites. Cause you turn the wrong account transfer case

open two django project to simulate the phenomenon of transfer of

how to distinguish between serious phishing sites and sites? In return decent website page when, in the form secretly plug form a special string, the back-end record value corresponding string change page, and other users send post request, I went to a special check character string matches

how to write this particular string of it? There is a fixed template syntax wording {% csrf_token%}, the form must be written in the form

browser to view the value of the label change, and every refresh. Demo again just transfers

ajax how to set csrf_token

`` `Python
to write on the first page of a # {% csrf_token%} tag, look back with jquery tag value consisting of key-value pairs can put data in
` ` `

csrf_token topical use

`` `Python
# just want to give a view of the Korean plus csrf check
from django.views.decorators.csrf Import csrf_exempt, csrf_protect

# local disabled
@csrf_exempt
DEF index (Request):
Pass

# topical
@csrf_protect
Login DEF (Request):
Pass

# the CBV special, not add on a separate method
# can only be applied on a class or method dispatch
from django.utils.decorators Import method_decorator
from django.views.decorators.csrf Import csrf_exempt, csrf_protect
@method_decorator (csrf_exempt, name = 'GET') # first
class csrf_token (View):
@method_decorator (csrf_exempt) # second
DEF dispatch (Self, Request, * args, ** kwargs):
RES = Super ( ) .dispatch (Request, * args, ** kwargs)
return RES
@method_decorator (csrf_exempt) # write here so not! ! !
GET DEF (Self, Request):
Pass
DEF POST (Self, Request):
Pass
`` `

# Auth authentication module

executing two commands that database migration, even if we do not build the table, django is not also create a lot of tables ? We went to look after you create a table called auth_user inside, since it is a table, it is certainly there should be a corresponding method of operation change table

auth_user add table records

- create a super user (not manually inserted, because the password is encrypted)

- Simple auth authentication using

`` `Python
from django.contrib Import auth
DEF Login (Request):
IF request.method == 'the POST':
name = request.POST.get ( 'name')
pwd = request.POST.get ( ' pwd ')
User auth.authenticate = (Request, name = username, password = pwd)
# = models.User.objects.filter similar User (name = username, password pwd =) .first ()
IF User:
redirect return ( '/ Home /')
return the render (Request, 'login.html')
`` `

- is simply not verify the information, but also to the successful landing of the user's current login status saved before by cookie or session, now then, auth also provides you with a more useful method

`` `Python
IF the User:
# equivalent to request.session [ 'name'] = name
auth.login (Request, the User) # landing, in fact, put user information into the session, the session run about verification table
`` `

- above and landing in fact not verify its highlights, highlights that

` `` Python
# long as the landing successfully executed auth.login (request, user)
after the # any other view functions are to get the current logged in user objects through request.user

# when no execution auth.login, request.user printed an anonymous user. The session table data can be deleted demonstration effect change
# request.user how to determine whether the user auth.login landing? request.user.is_authenticated

# Why after performing auth.login, view other functions you can get it through the current target landing request.user? Django middleware think there is no one called middleware Auth what it did a what, it can not be deduced? Remove the session to check the corresponding data table inside, then put request.user, the point to look into this middleware is true
`` `

- logout

` `` Python
auth.logout (request)
# equivalent of deleting session data request .session.flush ()
`` `

- decorator checks whether a jump landing and

` `` Python
from django.contrib.auth.decorators Import login_required

@login_required (LOGIN_URL = '/ login /', redirect_field_name = 'Old') # no login will jump to the login page and stitching on the back will be the last time you want to visit page path / login / next = / test / , you can modify the next key parameter name?
DEF my_view (Request):
pass
`` `

- If all the functions need to decorate my view and jump to the login page, then I need to write a lot of copies

`` `Python
# can be specified in the configuration file auth check illegal landing jump to a unified path
LOGIN_URL = ' / login / '# local configuration may be, may be configured globally
`` `

- back to the top, we are how to add data to auth_user table? ~ ~ ~ Command line is not reasonable?

`` Python `
from django.contrib.auth.models Import the User
DEF the Register (Request):
User.objects.create () # can not use this, because the password is expressly
User.objects.createuser () # Create a regular user
User.objects .createsuperuser () # create a super user
`` `

- check the password, change the password

` `` Python
request.user.check_password (pwd) # Why not get direct Access because the front-end user input is ciphertext plaintext database

request.user .set_password (pwd)
request.user.save () # change the password
`

#### custom table model application auth function

of how expansion auth_user table?

- one association (not recommended)

`` `Python
from django.contrib.auth.model S Import the User

class UserDetail (models.Models):
= models.CharField Phone (MAX_LENGTH =. 11)
User = models.OnoToOneField (= to the User)
`` `

- object-oriented inheritance

` `` Python
from the User django.contrib.auth.models Import, AbstractUser
class the UserInfo (AbstractUser):
= models.CharField Phone (max_length = 32)

# required in the configuration file, specify the default auth_user I no longer use my own table but created Userinfo table
AUTH_USER_MODEL = "app name .models table inside corresponding model name"


" ""
after a custom authentication system default data tables used, we can be used like the default auth_user table our UserInfo table of the.
library which did not auth_user table, the original method of operation auth table, and now all with a custom tables can be achieved
. "" "
` ``

'' '

Yesterday Recap 
CBV decorator
from django.utils.decorators import method_decorator
three ways
1. above plus class, need to specify the method to be decorated by the name parameter
@method_decorator (login_auth, name = 'GET')
2. directly want to decorate the method
@method_decorator (login_auth)
3. rewrite dispatch, dispatch directly to the installation (meaning the class methods are all decorated)
@method_decorator (login_auth)

django middleware
django portal / security
django exposed to the user can customize the method defined not
need to know:
process_request: time to turn down the request will be executed (if it returns an HttpResponse object in this method from
then go no follow-up will come with the middleware level process_response method sequentially up and return from)
process_response: response time will go up in order to perform from under (the response parameter needs to be returned)

need to know:
process_view: match before routing the successful implementation of the view function (if direct return an HttpResponse object, then he will turn up last middleware execution process_response from below)
process_exception: view the error function automatically triggers (from bottom)
process_template_response: when the object returned in a render method (or objects comprising a template_response)

custom middleware
create an arbitrary application in response to a folder, the folder py built an arbitrary file
from django.utils.deprecation import MiddlewareMixin
class MyMdzz (MiddlewareMixin):
DEF process_request (Self, request):
return None

DEF process_response (Self, request, Response):
return Response
disposed in the settings of
'application name folder file name class name...'

cross-site request forgery (CSRF)
form a form
{% csrf_token%}

Submit ajax
# first
Data:: { 'csrfmiddlewaretoken' $ ( '[name = "csrfmiddlewaretoken"]') Val ().}
# The second
Data: { 'csrfmiddlewaretoken': 'csrf_token {} {}'}

from Import csrf_exempt django.views.decorators.csrf, csrf_protect
from django.utils.decorators Import method_decorator

FBV:
@csrf_exempt
DEF index (Request):
return HttpResponse ( 'index')

CBV:

"" "
csrf_protect: CBV as you register with decoration "" "Three methods
csrf_exempt: this method can only dispatch means
@method_decorator (csrf_exempt, name = 'dispatch ') # First
class Index3 (View):
# @Method_decorator (csrf_exempt) # second
DEF dispatch (Self, Request, * args, ** kwargs):
. Super () dispatch (Request, * args, ** kwargs)
are actually to dispatch plus
"" "

auth module
from django.contrib import auth
create a super user
createsuperuser

function module associated with the user, the default action is to auth_user

# query the current user if there is (must pass a user name and password to verify if a user exists)
# equivalent to models.User. objects.filter (** kwargs) .first ()
USER_OBJ = auth.authenticate (Request, username = username, password = password)
# record the current user state
auth.login (request, user_obj) # is equivalent to request.session [ ' name '] = USER_OBJ
"" "
As long as the implementation of the auth.login (request, user_obj) you can get the currently logged-in objects through request.user at any position
. "" "
# Log
auth.logout (Request)
# Change Password
request.user.check_password ( 'jason123 ')
request.user.set_password (' jason666 ')
request.user.save ()
# registration function
from django.contrib.auth.models Import the User
User.objects.create (** kwargs) # becomes clear text password can not be used !
User.objects.create_user (** kwargs)
User.objects.create_superuser (** kwargs)


field extension table
# the first method one association table
Class UserDetail (models.Models):
Phone = ...
Avatar = ...
Detail = models.OneToOneField (to = 'the User')

# The second inherit real AbstractUser
class UserInfo (AbstractUser):
Phone = ...
Avatar = ...
PS: must tell django no longer in the configuration file with the default auth_user auth module to support the
AUTH_USER_MODEL = 'application name. table name '
AUTH_USER_MODEL =' app01.UserInfo '



# decorator
from django.contrib.auth.decorators Import login_required

@login_required (LOGIN_URL =' / Login / ') # local configuration
DEF index (Request):
return the HttpResponse (' index ')

global configuration #
# configuration file
LOGIN_URL = '/ login /'




















Guess you like

Origin www.cnblogs.com/huangxuanya/p/11079634.html