A brief introduction: validate user login
Two authentication mechanisms:
when information needs to be able 1 session session session_id acquired by the storage server, each request reaches the server, the key value session_id need to obtain information stored in the memory / disk / database
2 token token information were token inside, the server only needs to be resolved according to the algorithm defined in the token, you can obtain the necessary authentication information. So is a memory cost, a cost that Time
EG: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOjEsIm5iZiI6MTUyNjg4NjYzM30.CTZH48xD_TdtDZcgAd8exiCxkryXASruDCbRHsFFD5Y
three About JWT
JWT (Json Web Token) authentication token is to achieve a common standard.
Installation JWT four global authentication setting
a Plug
PIP3 the install djangorestframework JWT-
2 Setting the global settings
to be noted here, will verify that all VIEW
REST_FRAMEWORK = {
# certification authority
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
# authentication
' DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
' rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
五 整体使用
1 登录完成后自动生成token并返回前端
from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
user = Account.objects.filter(username=username).first()
payload = jwt_payload_handler(user)
= jwt_encode_handler token (payload)
return the Response { 'token': token}
Note: user django herein for carrying queryset user queries, there must be
two variables distal VUEX read and stored in a global variable
3 according to a global distal vue Construction of each variable api access request.header
IF (store.getters.token) {
the console.log ( 'can enter')
config.headers [ 'Authorization'] = 'the JWT' getToken to + ()
}
Note: this token format is jwt + token, authorization and lower case must
be tested api port 4
Six related rights
1 default role
1 AllowAny letting all
2 IsAuthenticated to verify the release of only
3 IsAdminUser super administrator
4 IsAuthenticatedOrReadOnly will allow the user to perform any authenticated request. Only when the request method is "safe" methods (GET, HEAD or OPTIONS) When one of only allows users to request unauthorized.
2 custom permission
to implement custom privileges, and implement an override BasePermission or both of the following methods
.has_permission (Self, Request, View)
.has_object_permission (Self, Request, View, obj)
. 1 If the request is granted access authority, the method should return True, otherwise return False
2 only if the view level has_permission check passes, will call an instance method level has_object_permission