📌  相关文章
📜  rest_framework_simplejwt - Python (1)

📅  最后修改于: 2023-12-03 14:47:04.710000             🧑  作者: Mango

Introduction to rest_framework_simplejwt

rest_framework_simplejwt is a Python library that provides a simple and powerful Token-based authentication system for APIs built using Django REST framework.

Features
  • Easy integration with Django REST framework.
  • Stateless, JSON web tokens (JWT) based authentication.
  • Token refreshing and revoking.
  • Token blacklisting.
  • Multiple token types (access, refresh).
Installation

To install rest_framework_simplejwt, you can use pip:

pip install djangorestframework_simplejwt
Usage

Configuration

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',
    ),
}

Generating Token

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'

Refreshing 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>"
# }

Revoking Token

To revoke a token:

from rest_framework_simplejwt.tokens import RefreshToken

def revoke_token(token):
    try:
        RefreshToken(token).blacklist()
    except TokenError:
        pass

Blacklisting Token

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), 
}
Conclusion

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.