📜  django 设置中的 simplejwt (1)

📅  最后修改于: 2023-12-03 15:00:27.481000             🧑  作者: Mango

Django SimpleJWT

Django SimpleJWT is a JSON Web Token authentication plugin for Django REST Framework. It allows users to obtain a JSON Web Token after providing their credentials and use that token for subsequent authentication.

Features
  • Fully customizable token endpoint
  • JTI (JWT ID) validation
  • Time-based tokens (JWT_EXPIRATION_DELTA)
  • Token refresh functionality
  • Blacklisting/revoking tokens
  • User-defined token response JSON keys
  • Symmetric key signing with a secret key
  • Asymmetric key signing with public/private keys
Installation

You can install SimpleJWT using pip. Just run the following command in your terminal.

pip install djangorestframework-simplejwt
Usage

Add SimpleJWT to your Django app's INSTALLED_APPS:

INSTALLED_APPS = [
    # ...,
    'rest_framework_simplejwt',
]

Add the following configuration to your Django app's settings.py file.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

You can customize the TokenObtainPairView view by creating a subclass and specifying the desired values for the following attributes:

from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer
    token_obtain_pair_kwargs = {'expires_in': '5 minutes'}
    response = {'access_token': 'token', 'token_type': 'bearer')

To refresh a token, you can send a POST request to the TokenRefreshView endpoint with the expired token in the Authorization header.

curl -X POST -H "Authorization: Bearer <expired_token>" http://localhost:8000/token/refresh/

For more information about how to use SimpleJWT, please refer to the official documentation.

Conclusion

Django SimpleJWT is a simple and powerful authentication plugin that is easy to integrate into your Django REST Framework app. It provides an easy way to manage user authentication and authorization using JSON Web Tokens. With its impressive features and flexibility, it’s definitely worth considering for your next Django project.