📌  相关文章
📜  django rest framework simple jwt - Python (1)

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

Django REST Framework Simple JWT

Django REST Framework Simple JWT is a library for adding JSON Web Token authentication to Django REST Framework APIs. It offers a simple and secure way to authenticate users and protect API endpoints.

Installation

To install Django REST Framework Simple JWT, use pip:

pip install djangorestframework-simplejwt
Usage
Configuring JWT settings

Before using JWT authentication, you need to configure the JWT settings in your Django settings file. The following settings are available:

# The secret key used to sign the JWT
SECRET_KEY = 'your-secret-key'

# The token expiration time (in seconds)
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}
Obtaining tokens

To obtain JWT tokens, you need to send a POST request to the token endpoint with valid login credentials. The token endpoint is typically located at /api/token/.

from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

To use the default token serializer, you can simply do:

from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairView(TokenObtainPairView):
    pass
Using tokens

Once you have obtained JWT tokens, you can use them to access protected API endpoints by including the access token in the HTTP Authorization header.

import requests

url = 'https://api.example.com/users/'
headers = {
    'Authorization': 'Bearer <access_token>'
}
response = requests.get(url, headers=headers)
Refreshing tokens

JWT access tokens have a short lifespan by design. Once a token expires, you need to obtain a new one to continue accessing protected endpoints. To avoid prompting the user to log in again, you can use a refresh token to obtain a new access token.

To refresh a token, you need to send a POST request to the token refresh endpoint with a valid refresh token. The token refresh endpoint is typically located at /api/token/refresh/.

from rest_framework_simplejwt.views import TokenRefreshView

class MyTokenRefreshView(TokenRefreshView):
    pass
Customizing token claims

You can customize the claims of the JWT tokens by creating a custom token encoder. The following example customizes the email claim of the access token.

from rest_framework_simplejwt.tokens import AccessToken

class MyAccessToken(AccessToken):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.payload['email'] = self.user.email

To use the custom token encoder, set the ACCESS_TOKEN_CLS setting in your Django settings file.

SIMPLE_JWT = {
    'ACCESS_TOKEN_CLS': 'myapp.tokens.MyAccessToken',
    ...
}
Conclusion

Django REST Framework Simple JWT provides a simple and secure way to authenticate users and protect API endpoints using JSON Web Tokens. With its easy-to-use API and powerful customization options, it is a great choice for any Django REST Framework project.