Package: django-jwt-extended
Django-JWT-ExtendedImplement JWT authentication with Django quickly and easily!Inspired byflask-jwt-extended.InstallationPip:pip install django-jwt-extendedAfter that, adddjango_jwt_extendedtoINSTALLED_APPSsettings.INSTALLED_APPS = [
    ...
    'django_jwt_extended',
]Get Starteddjango-jwt-extendedmakes it easy and simple to create authentication feature.Startup your project$pipinstalldjango
$pipinstalldjango-jwt-extended
$django-adminstartprojectexample.
$pythonmanage.pymigrate
$pythonmanage.pycreatesuperuserEdit your views# views.pyfromdjango.httpimportJsonResponsefromdjango_jwt_extendedimportjwt_requiredfromdjango_jwt_extendedimportcreate_access_tokenfromdjango_jwt_extendedimportget_jwt_identitydeflogin(request):"""Create JWT Token API"""returnJsonResponse({"access_token":create_access_token(identity="iml"),})@jwt_required()defuser(request):"""JWT Authentication API"""identity=get_jwt_identity(request)# "iml"returnJsonResponse({'id':identity,})Advanced UsageThis section goes into more detail about django-jwt-extended.Return with refresh tokenIf you want to return not only the access token but also the refresh token, you can use it as follows.Identityis input as an argument to generate tokens.ThisIdentitycan contain any object thatcan be serialized as json, and is stored in "sub" of JWT Schema.fromdjango_jwt_extendedimportcreate_access_tokenfromdjango_jwt_extendedimportcreate_refresh_token# Login and issue tokensdeflogin(request):returnJsonResponse({"access_token":create_access_token("iml"),'refresh_token':create_refresh_token('iml'),})Refresh Token AuthenticationWhen you want to perform authentication through refresh token, Set the refresh argument toTrueas shown below.# Refresh tokens@jwt_required(refresh=True)# refresh token checkdefrefresh(request):identity=get_jwt_identity(request)returnJsonResponse({"access_token":create_access_token(identity),'refresh_token':create_refresh_token(identity),})Parse JWT PayloadThere are two ways to get the contents of jwt token. These areget_jwt_identityandget_jwt.get_jwt_identityreturns the identity value given when creating the token as it is.get_jwtreturns the full payload that decoded the jwt token.# Authentication access token@jwt_required()defuser(request):identity=get_jwt_identity(request)payload=get_jwt(request)returnJsonResponse({'id':identity,'raw_jwt':payload,})Optional AuthenticationIf the optional argument isTrue, the verification step is passed even if the corresponding token does not exist. However, in this case, even ifidentity or jwt payloadis called,Noneis returned.# Optional Login example@jwt_required(optional=True)defuser_optional(request):identity=get_jwt_identity(request)returnJsonResponse({'id':identity})Custom Decorator PatternIf it is cumbersome to implement thejwt_requiredlogic repeatedly every time, you can implement a custom decorator as shown below. This is only an example, and more various methods may exist.# Authentication access token with Decoratordeflogin_required(func):@jwt_required()defwrapper(request,**path):identity=get_jwt_identity(request)request.META['logined_identity']=identity# before requestresponse=func(request,**path)request.META.pop('logined_identity')# after requestreturnresponsereturnwrapper@login_requireddefdecorator_user(request):identity=request.META['logined_identity']payload=get_jwt(request)returnJsonResponse({'id':identity,'raw_jwt':payload,})ConfigurationEven if you don't configure anything, your app works.But insettings.pyin your app, You can customize your app through the following settings.Here's a good sample.# settings.pySECRET_KEY="super-secret"JWT_CONFIG={'ALGORITHM':'HS256','LOCATION':['headers'],'ACCESS_TOKEN_EXPIRES':timedelta(days=2),'REFRESH_TOKEN_EXPIRES':timedelta(days=30),'JWT_NOT_FOUND_MSG':{'msg':"can't find JWT token."}}...SECRET_KEYThis is the secret key setting that Django supports by default.Django-jwt-extendedalso, the key is used when encoding/decoding JWT.JWT_CONFIGJWT_CONFIGis a setting added fordjango_jwt_extended.Additional settings can be added as follows in the form of a dictionary.ALGORITHMALGORITHM: "HS256"Default:HS256Allowed_values:HS256Select the encode/decode algorithm to issue tokens. (Currently only 'HS256' is supported)LOCATIONLOCATION: ["headers", ...]default:["headers"]allowed_values:headers,cookiesThis setting determines where to collect the Tokens. The thing to note is thatinput is received as a list, not as a single string. You can pass in a list to check more then one location, for example["headers", "cookies"]. The order of the list sets the precedence of where JWTs will be looked for.headersFor headers, the header name is fixed to"Authorization", and the token format is"Bearer [token]".cookiesIn the cookie, you can directly specifythe cookie name for the access tokenandthe cookie name for the refresh token.ACCESS_TOKEN_COOKIE_NAMEACCESS_TOKEN_COOKIE_NAME: access_tokenDefault:access_tokenAllowed_types:stringThe name of the cookie that will store the access token.REFRESH_TOKEN_COOKIE_NAMEREFRESH_TOKEN_COOKIE_NAME: refresh_tokenDefault:refresh_tokenAllowed_types:stringThe name of the cookie that will store the refresh token.ACCESS_TOKEN_EXPIRESACCESS_TOKEN_EXPIRES: 60 * 24 * 2 # 2daysDefault:60 * 24 * 2Allowed_types:integer,datetime.timedeltaHow long an access token should be valid before it expires. This can be a a number of seconds (Integer).REFRESH_TOKEN_EXPIRESREFRESH_TOKEN_EXPIRES: 60 * 24 * 30 # 1monthDefault:60 * 24 * 30Allowed_types:integer,datetime.timedeltaHow long a refresh token should be valid before it expires. This can be a number of seconds (Integer).Custom Error Responses<CUSTOM_ERROR_RESONSE>: {msg: "custom-error"}Default:[json-object]Allowed_types:Dict (json serializable)When your app encounters different situations, it returns different error responses with 401.JWT_NOT_FOUND_MSGReturned when you can't find the token in any locations.DECODE_ERROR_MSGReturned when the Token signature value is invalid.EXPIRED_TOKEN_MSGReturned when the corresponding token has expired.INVALID_TOKEN_TYPE_MSGReturned when an unexpected token type (access or refresh).TOKEN_TYPE_NOT_FOUND_MSGReturned when it doesn't our meet our JWT Standards.INVALID_NBF_MSGReturned when the nbf value does not exceed the current time.BEARER_ERROR_MSGReturned if token was found in Header, but does not start with Bearer.