djangorestframework-simplejwtでJWTのclaimをカスタマイズする方法

2021/05/11に公開

djangorestframework-simplejwtでJWTのclaimをカスタマイズする方法です。

概要

2点説明。
(1)Claimをカスタマイズするためのクラスを作成し、トークンを生成
(2)トークンからユーザーの取得

(1)Claimをカスタマイズするためのクラスを作成し、トークンを生成

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


class CustomJwtToken(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # ここで追加したいキーを設定し、データを代入
        token['custom_key'] = user.custom_key
	
	# 最後トークンを返す
        return token

# ユーザーからJWTトークンを返す。
def create_jwt(user):
    token = CustomJwtToken.get_token(user)
    
    #アクセストークンを返す
    return token.access_token

(2)トークンからユーザーの取得

from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication
from rest_framework_simplejwt.authentication import JWTAuthentication

token = create_jwt(user)

jWTTokenUserAuthentication = JWTTokenUserAuthentication()
jWTAuthentication = JWTAuthentication()
try:
    user_token = jWTTokenUserAuthentication.get_user(jWTAuthentication.get_validated_token(str(token)))
except:
    #ユーザー を取得できなかった時の対応
    
#ユーザー情報の取得
user = user.token
print(user["user_id"])
print(user["custom_key"])


djangorestframework-simplejwtのインストール方法はこちらから
https://zenn.dev/kiiimii/articles/b1766f4beba958

Discussion