Python implements authentication mechanism process analysis based on jwt

1 . Jwt advantages and disadvantages

Advantages of jwt:

1. It is very convenient to implement distributed single sign-on

2. The data is actually stored on the client, so we can share the storage pressure of the database or server

Disadvantages of jwt:

1. The data is stored on the client. Our server only recognizes jwt, not the client. 2. Jwt can set the expiration time, but because the data is stored on the client, it is not easy to adjust the expiration time.

2. Install jwt

pip install djangorestframework-jwt -i https://pypi.douban.com/simple

3. In settings.dev

REST_FRAMEWORK = {
  'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
  ),
}
import datetime
JWT_AUTH = {
  'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), ##Set the valid value of token
}


4. Manually generate jwt

from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
 
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)


5. The backend implements the login authentication interface (in the sub-application routing urls.py)

from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
  path(r'login/', obtain_jwt_token), ##Provide interface
]


6. Custom return data, (under the path of user.utils.jwt_response_payload_handler)

def jwt_response_payload_handler(token, user=None, request=None):
  """
  Custom JWT authentication returns data successfully
  """
  return {
    'token': token,
    'id': user.id,
    'username': user.username
  }#This is the custom jwt authentication successfully returned data, which will generally be placed in the utils file under the sub-application, and then configured in the settings, and tell django the path


7. Modify the settings.dev configuration file

# JWT
JWT_AUTH = {
  'JWT_EXPIRATION_DELTA': datetime.timedelta (days = 1),
  'JWT_RESPONSE_PAYLOAD_HANDLER': 'user.utils.jwt_response_payload_handler',
}


The above is the whole content of this article, I hope it will be helpful to everyone's study, and I hope you can support it.


Guess you like

Origin blog.51cto.com/14825302/2547219