📅  最后修改于: 2023-12-03 14:47:04.710000             🧑  作者: Mango
rest_framework_simplejwt is a Python library that provides a simple and powerful Token-based authentication system for APIs built using Django REST framework.
To install rest_framework_simplejwt, you can use pip:
pip install djangorestframework_simplejwt
In order to use rest_framework_simplejwt, you'll need to add the library to your INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework_simplejwt',
...
]
Add the authentication classes in REST_FRAMEWORK setting:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
Generate a token for the user with valid credentials:
from rest_framework_simplejwt.views import TokenObtainPairView
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer
# set authentication rate limit
throttle_scope = 'login_token'
# Json response will be like:
#{
# "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYyMzkwMjJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
# "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYyNDI2MjJ9.W4h26uxAHm5vQNekm44hBJQTHisJ-7X9dIl5pyMfALc"
#}
Check token with this API endpoint:
from rest_framework_simplejwt.views import TokenVerifyView
class MyTokenVerifyView(TokenVerifyView):
# set authentication rate limit
throttle_scope = 'verify_token'
To obtain a new access token with a valid refresh token:
from rest_framework_simplejwt.views import TokenRefreshView
class MyTokenRefreshView(TokenRefreshView):
# set authentication rate limit
throttle_scope = 'refresh_token'
# Json response will be like:
# {
# "access": "<new_access_token>",
# "refresh": "<new_refresh_token>"
# }
To revoke a token:
from rest_framework_simplejwt.tokens import RefreshToken
def revoke_token(token):
try:
RefreshToken(token).blacklist()
except TokenError:
pass
To use token blacklist, add blacklist to your settings.py:
SIMPLE_JWT = {
'BLACKLIST': {
'ENABLED': True,
'REDIS_CONNECTION': 'redis://localhost:6379/0',
'PREFIX': 'jwt:blacklist:',
'SIGNATURE_NEEDED': False,
'ROTATE_REFRESH_TOKENS':False
}
}
To limit the lifetime of the token and refresh token:
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}
rest_framework_simplejwt is a powerful library for adding simple token-based authentication to your Django REST framework API. It provides features like token refreshing, revoking, blacklisting and multiple token types. The library is easy to configure and use, making it an excellent choice for developers building RESTful APIs.