当前位置:网站首页>JWT token related configuration (global configuration identity authentication rewrites authenticate method)
JWT token related configuration (global configuration identity authentication rewrites authenticate method)
2022-07-29 00:48:00 【:D...】
List of articles
- One . jwt Global configuration
- 1.settings To configure
- Two . To configure jwt Expiration time Custom returned json data
- 1.utils.py Function writing , Returns the specified format json data
- 2.settings To configure
- 3、 ... and . To configure django Authentication back end of The purpose is to allow only administrators to log in Customize an authentication class rewrite Authenticate Method
- 1.utils.py Class writing rewrite Authenticate Method
- 2.settings To configure
- Four . Routing configuration
- 5、 ... and . Model class
- 1.models.py Define user classes in
- 2.settings To configure
- 3 Add test data
One . jwt Global configuration
1.settings To configure
REST_FRAMEWORK = {
# Identity Authentication
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',),
}
import datetime
JWT_AUTH = {
# jwt Expiration time difference 3 Days overdue
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=3),
# Custom returned json data **** Next, join
'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.utils.jwt_response_payload_handler',
}
Two . To configure jwt Expiration time Custom returned json data
1.utils.py Function writing , Returns the specified format json data
users.utils.jwt_response_payload_handler: Created in users app Under the utils.py Of jwt_response_payload_handler function
Be careful : jwt_response_payload_handler The function needs to be written
stay users app Create utils.py Then write
# Returns the specified format json data token
def jwt_response_payload_handler(*args, **kwargs):
print('args:', args)
print('kwargs:', kwargs)
token, user, request = args
return {
'code': 200,
'username': user.username,
'user_id': user.id,
'token': token
}
2.settings To configure
settings In the configuration file
import datetime
JWT_AUTH = {
# jwt Expiration time difference 3 Days overdue
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=3),
# Custom returned json data
'JWT_RESPONSE_PAYLOAD_HANDLER': 'users.utils.jwt_response_payload_handler',
}
3、 ... and . To configure django Authentication back end of The purpose is to allow only administrators to log in Customize an authentication class rewrite Authenticate Method
users.utils.MyAuthentication: Created in users app Under the utils.py Of MyAuthentication class
Be careful : MyAuthentication Class needs to be written Inherit authentication parent ModelBackend
1.utils.py Class writing rewrite Authenticate Method
stay users app Create utils.py Then write
# Only let administrators log in
class MyAuthentication(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
# Query user objects You can login through password and mobile number
user = User.objects.filter(Q(username=username) | Q(phone=username)).first()
# Judge user , password , Administrator or not
if user and check_password(password, user.password) and user.is_staff:
return user # Verify that the object is returned Otherwise return to None
else:
return None
2.settings To configure
settings In the configuration file
AUTHENTICATION_BACKENDS = [
'users.utils.MyAuthentication', # Custom authentication
]
Four . Routing configuration
Do not inherit view classes , It is obtain_jwt_token
The interface shall be modified according to specific needs
urlpatterns = [
# Administrator login authentication
path('login/', obtain_jwt_token),
]
5、 ... and . Model class
1.models.py Define user classes in
# User class
class User(AbstractUser):
phone = models.CharField(' cell-phone number ', max_length=11, null=True, unique=True, blank=True)
last_login = models.DateTimeField(' Last login ', null=True, blank=True)
def __str__(self):
return self.username
class Meta:
db_table = "user_tb"
verbose_name_plural = ' User table '
2.settings To configure
# Authenticated user model class
AUTH_USER_MODEL = 'users.User'
3 Add test data
adopt python manage.py shell Ciphertext addition 
边栏推荐
- Tips for API interface optimization
- MySQL stored procedure
- Installation and use of pnpm
- Meeting notification & meeting feedback & feedback details function of meeting OA project
- Upload Excel files with El upload and download the returned files
- Api 接口优化有哪些技巧?
- IMG tags prohibit dragging pictures
- AQS原理
- Rk3399 9.0 driver add powser button
- flask与七牛云上传图片
猜你喜欢
随机推荐
SurfaceControl和SurfaceFlinger通信
刷题的第三十天
Dynamic programming problem (1)
Brief introduction to compressed sensing
PTA (daily question) 7-72 calculate the cumulative sum
17. Design of machine learning system
乱打日志的男孩运气怎么样我不知道,加班肯定很多!
CUDA相关
rk3399 9.0驱动添加Powser按键
AQS原理
Application and principle of distributed current limiting redistribution rratelimiter
How to learn R language
armeabi-v7a架构(sv7a)
Api 接口优化有哪些技巧?
CUDA related
C语言括号匹配(栈括号匹配c语言)
seleniumwire获取百度指数
Dynamic programming problem (VII)
Api 接口优化的那些技巧
数学建模及其基础知识详解(化学常考知识点)








