JWT Authentication
JWT authentication can solve the problems of HTTP stateless authentication and cross-domain login. It is often used in the solution of logging in with the same account on different domain name pages. In Django, JWT can be used instead of Session for authentication. Session is generally saved in the database of the server, while JWT saves the authentication result in the cookie in the form of Token, and there is a difference between the two in terms of saving
accomplish
- pyjwt 2.4.0
The implementation code is as follows:
class JWTAuth(View):
"""create token and decode token"""
def post(self, request, *args, **kwargs):
username = request.POST.get('username')
password = request.POST.get('password')
# check username and password
user = authenticate(request, username=username, password=password)
if user is not None and user.is_active:
# use get_jwt_token to create a token
jwt_token = self.get_jwt_token(username)
return JsonResponse({
"jwt_toke":jwt_token})
return JsonResponse({
"message":"check name and password"})
def get(self, request):
headers = request.headers
# check jwttoken in headers or not
if 'jwttoken' in headers:
# decode token
if self.decode_jwt_token(headers['jwttoken']):
return JsonResponse({
"message":"This is Auth page!"})
else:
return JsonResponse({
"error":"You get a wrong token"})
else:
return JsonResponse({
"error":"You dont have token"})
return JsonResponse({
"message":"this is token page!"})
@staticmethod
def get_jwt_token(username):
"""crete jwt token"""
payload={
# Set the expiration time for example 3600 seconds
'exp':datetime.datetime.utcnow() + datetime.timedelta(3600),
'iat':datetime.datetime.utcnow(),
'data':{
'username':username},
}
# payload:payload
# string:salt
# algorthm:encryption method
encode_jwt = jwt.encode(payload, "jfjufcb37%jfjoeo", algorithm='HS256')
return encode_jwt
@staticmethod
def decode_jwt_token(encode_jwt):
"""decode jwt """
result = jwt.decode(encode_jwt,"jfjufcb37%jfjoeo", algorithms=['HS256'])
return result
Summary of various error reporting problems in DRF
serializers.CurrentUserDefault error prompt request error
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-qoNk2CQD-1666513909338)(https://img-blog.cksdnimg.cn/461480b42c234a3a9146f5fa1b97289b.png)] by
viewing Error message, it can be known that
when this class is called, the user value of the request object is obtained through the context context and returned. After setting a breakpoint, it is found that the context is an empty dictionary when accessing. Naturally, the value of the key key of request cannot be obtained. You can get it by querying the official document As you know, the request needs to be passed in as a context dictionary when the serializer is initialized,
so just add a context dictionary to the view layer.
The above sample codes are all from @大江狗