[PYTHON] [Django] JWT notes

Settings in Settings.py

REST_FRAMEWORK

``` REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( #Load Simple JWT 'rest_framework_simplejwt.authentication.JWTAuthentication', ), # } ```

Load Simple JWT here

SIMPLE_JWT

SIMPLE_JWT = {
    #Set the token time to 5
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=14),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': False,
    #Cryptographic algorithm settings
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUTH_HEADER_TYPES': ('JWT',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
}

ACCESS_TOKEN_LIFETIME

>A datetime.timedelta object which specifies how long refresh tokens are valid. This timedelta value is added to the current UTC time during token generation to obtain the token’s default “exp” claim value. Source: django-rest-framework-simplejwt.readthedocs.io

Specify the token renewal period with timedelta. You will need to log in again after the period expires.

REFRESH_TOKEN_LIFETIME

A datetime.timedelta object which specifies how long refresh tokens are valid. This timedelta value is added to the current UTC time during token generation to obtain the token’s default “exp” claim value. Source: django-rest-framework-simplejwt.readthedocs.io

Almost the same as ACCESS_TOKEN_LIFETIME But I'm not sure why I change both at different times

ROTATE_REFRESH_TOKENS

>When set to True, if a refresh token is submitted to the TokenRefreshView, a new refresh token will be returned along with the new access token. This new refresh token will be supplied via a “refresh” key in the JSON response. New refresh tokens will have a renewed expiration time which is determined by adding the timedelta in the REFRESH_TOKEN_LIFETIME setting to the current time when the request is made. If the blacklist app is in use and the BLACKLIST_AFTER_ROTATION setting is set to True, refresh tokens submitted to the refresh view will be added to the blacklist. Source: django-rest-framework-simplejwt.readthedocs.io

If it is True and a refresh token is sent to the Token Refresh View, a new refresh token will be issued. Blacklist app? ?? If sent from, the refresh token will be blacklisted

BLACKLIST_AFTER_ROTATION

>When set to True, causes refresh tokens submitted to the TokenRefreshView to be added to the blacklist if the blacklist app is in use and the ROTATE_REFRESH_TOKENS setting is set to True. You need to add 'rest_framework_simplejwt.token_blacklist', to your INSTALLED_APPS in the settings file to use this settings. Source: django-rest-framework-simplejwt.readthedocs.io

ALGORITHM

>The algorithm from the PyJWT library which will be used to perform signing/verification operations on tokens. To use symmetric HMAC signing and verification, the following algorithms may be used: 'HS256', 'HS384', 'HS512'. When an HMAC algorithm is chosen, the SIGNING_KEY setting will be used as both the signing key and the verifying key. In that case, the VERIFYING_KEY setting will be ignored. To use asymmetric RSA signing and verification, the following algorithms may be used: 'RS256', 'RS384', 'RS512'. When an RSA algorithm is chosen, the SIGNING_KEY setting must be set to a string that contains an RSA private key. Likewise, the VERIFYING_KEY setting must be set to a string that contains an RSA public key. Source: django-rest-framework-simplejwt.readthedocs.io

Specify the algorithm used for authentication

SIGNING_KEY

>The signing key that is used to sign the content of generated tokens. For HMAC signing, this should be a random string with at least as many bits of data as is required by the signing protocol. For RSA signing, this should be a string that contains an RSA private key that is 2048 bits or longer. Since Simple JWT defaults to using 256-bit HMAC signing, the SIGNING_KEY setting defaults to the value of the SECRET_KEY setting for your django project. Although this is the most reasonable default that Simple JWT can provide, it is recommended that developers change this setting to a value that is independent from the django project secret key. This will make changing the signing key used for tokens easier in the event that it is compromised. Source: django-rest-framework-simplejwt.readthedocs.io

It's OK if you insert the secret key for the time being

VERIFYING_KEY

>The verifying key which is used to verify the content of generated tokens. If an HMAC algorithm has been specified by the ALGORITHM setting, the VERIFYING_KEY setting will be ignored and the value of the SIGNING_KEY setting will be used. If an RSA algorithm has been specified by the ALGORITHM setting, the VERIFYING_KEY setting must be set to a string that contains an RSA public key. Source: django-rest-framework-simplejwt.readthedocs.io

Required when using the RSA algorithm. Not needed this time

AUTH_HEADER_TYPES

>The authorization header type(s) that will be accepted for views that require authentication. For example, a value of 'Bearer' means that views requiring authentication would look for a header with the following format: Authorization: Bearer . This setting may also contain a list or tuple of possible header types (e.g. ('Bearer', 'JWT')). If a list or tuple is used in this way, and authentication fails, the first item in the collection will be used to build the “WWW-Authenticate” header in the response. Source: django-rest-framework-simplejwt.readthedocs.io

I'm not sure how to grant permissions on Views

USER_ID_FIELD

>The database field from the user model that will be included in generated tokens to identify users. It is recommended that the value of this setting specifies a field that does not normally change once its initial value is chosen. For example, specifying a “username” or “email” field would be a poor choice since an account’s username or email might change depending on how account management in a given service is designed. This could allow a new account to be created with an old username while an existing token is still valid which uses that username as a user identifier. Source: django-rest-framework-simplejwt.readthedocs.io

It is recommended to use an immutable value such as the primary key.

If id is specified, the primary key of user models will be set by default.

USER_ID_CLAIM

The claim in generated tokens which will be used to store user identifiers. For example, a setting value of 'user_id' would mean generated tokens include a “user_id” claim that contains the user’s identifier. Source: django-rest-framework-simplejwt.readthedocs.io

Used to store the number that identifies the user

AUTH_TOKEN_CLASSES

A list of dot paths to classes that specify the types of token that are allowed to prove authentication. More about this in the “Token types” section below. Source: django-rest-framework-simplejwt.readthedocs.io

List of token types used for authentication

TOKEN_TYPE_CLAIM

>The claim name that is used to store a token’s type. More about this in the “Token types” section below Source: django-rest-framework-simplejwt.readthedocs.io

Clame name for storing tokens

Serializers settings

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework import serializers
from .models import CustomUser

#I will explain this class first
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    @classmethod
    def get_token(cls, user):
        token = super(MyTokenObtainPairSerializer, cls).get_token(user)

        # Add custom claims
        token['fav_color'] = user.fav_color
        return token

class CustomUserSerializer(serializers.ModelSerializer):
    """
    Currently unused in preference of the below.
    """
    email = serializers.EmailField(
        required=True
    )
    username = serializers.CharField()
    password = serializers.CharField(min_length=8, write_only=True)

    class Meta:
        model = CustomUser
        fields = ('email', 'username', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)  # as long as the fields are the same, we can just use this
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

TokenObtainPairSerializer

This time customize only where you receive the token Enter your username and password and the token will be passed

CustomUserSerializer(serializers.ModelSerializer):

It's like a form model, and this time we will perform the process for registering a new user.

Views

ObtainTokenPairWithColorView(TokenObtainPairView)

A class that returns a token when posting login information No special settings are required here

CustomUserCreate(APIView)

``` permission_classes = (permissions.AllowAny,)
def post(self, request, format='json'):
    serializer = CustomUserSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.save()
        if user:
            json = serializer.data
            return Response(json, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

 A class for registering users.

 Only the processing when the information of new registration is posted is described.

 Get has no problem by default.


 <h2> Reference site </h2>
<a href="https://hackernoon.com/110percent-complete-jwt-authentication-with-django-and-react-2020-iejq34ta">110% Complete JWT Authentication with Django & React - 2020</a>


Recommended Posts

[Django] JWT notes
django notes
Django notes
[Django] as_view () notes
Django Template notes
Celery notes on Django
[Django] Directory structure practices + notes
Launch notes for existing Django applications
django update
Django note 4
Step notes to get started with django
JetBrains_Learning Notes_003
Django memorandum
django search
Django installation
SQLAlchemy notes
Django Summary
pyenv notes
Django test
Miscellaneous notes about the Django REST framework
Notes on creating static files in Django
Django # 2 (template)
SQL notes
Pandas notes
Sphinx notes
Django hands-on
Touch django
Django Summary
Django basics
Django defaults
Jupyter_Learning Notes_000
Django + Docker
Django Glossary
Django search
Django: References
Django Note 1
Django note 3
Django novice addicted error and solution notes
Django startup
Django NullCharField
Implement JWT login functionality in Django REST framework