Definition 1.

Json Web Token (JWT) is an open jSON-based standard (RFC 7519) implemented for the transfer of declarations between network application environments. The token is designed to be compact and secure, especially suitable for single sign-on (SSO) scenarios in distributed sites. The JWT declaration is generally used to pass authenticated user identity information between the identity provider and the service provider to obtain resources from the resource server, and to add some additional declaration information necessary for other business logic. The token can also be used directly for authentication or can be encrypted.

2. Traditional Session authentication

2.1 process

The session authentication process is as follows:

  1. The user sends the user name and password to the server.

  2. After the authentication, the server saves relevant data in the current session, such as user role, login time, and so on.

  3. The server returns a session_ID to the user and writes the user’s Cookie.

  4. The session_id is passed back to the server via cookies with each subsequent request from the user.

  5. The server receives the session_id, finds the previously saved data, and learns the user’s identity.

2.2 disadvantages

  • Sessions are stored on the server, which increases the overhead of the server when there are many registered users.

  • After the user is authenticated, the server makes authentication records. If the authentication records are stored in memory, it means that the user’s next request must be made on this server to obtain authorized resources, which limits the load balancing capability in distributed applications. This also means limiting the application’s ability to scale.

  • Session is based on cookies to identify users. If cookies are intercepted, users are vulnerable to cross-site request forgery (CSRF) attacks.

3. JWT certification

3.1 token

Similar to HTTP, THE token-based authentication mechanism of JWT is stateless. It does not need to retain user authentication information or session information on the server. This means that token-based applications do not need to consider which server users log in to, which facilitates application expansion.

3.2 process

  1. The user requests the server using a username and password

  2. The server authenticates the user’s information

  3. The server sends the user a token through authentication

  4. The client stores the token and supplies it with each request

  5. The server validates the token value and returns data

Access-control-allow-origin: * This token must be passed to the server on every request. It should be stored in the header of the request. In addition, the server must support the CORS policy.

3.3 JWT constitute

JWS is an implementation of JWT. In addition to JWS, JWE(JSON Web Encryption) is also an implementation of JWT. The generation process of JWE is relatively complex. Although security is guaranteed, access efficiency is reduced. The following mainly introduces an implementation method of JWT –JWS.

The first part is called the header, the second part is called the payload, and the third part is the signature.

Official link jwt.io/

header

The header of the JWT carries two pieces of information:

  • Declare type, in this case JWT

  • Algorithms that declare encryption usually use SHA256 directly

{"alg": "HS256", "TYp ": "JWT"}Copy the code

Base64 encryption of the header, which can be decrypted symmetrically, forms the first part. The resulting encrypted message is a string like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9Copy the code
payload

The payload is where the useful information is stored. This valid information consists of three parts:

  • A declaration of registration in a standard

  • Public statement

  • Private declaration

{  "name": "John"."admin": true, "email" :"[email protected]"}Copy the code

This part is also base64 encrypted, resulting in the following string:

ewogICJuYW1lIjogIkpvaG4iLAogICJhZG1pbiI6IHRydWXvvIwKICDigJxlbWFpbOKAnToieHh4QGdtYWlsLmNvbSIKfQCopy the code
signature

The third part of the JWT is a visa information, which consists of three parts:

  • Header (Base64 encryption)

  • Payload (Base64 encryption)

  • Secret key

This part is used by the base64-encrypted header and the Base64-encrypted payload. A string of concatenations, followed by SHA256 combined encryption (irreversible encryption) using the encryption declared in the header, constitutes the third part of the JWT. These three parts are concatenated into a complete string that forms the final JWT.

Note:secretIs stored on the server side,jwtIs also on the server side,secretIs used to carry outjwtThe issue andjwtTherefore, it is your server’s private key and should not be disclosed in any scenario. Once the client learns of thissecretThat means the client can self-signjwt. If you think the key is leaked, modify it in time.

4. Background Settings

The following is a JWT integration solution based on the djangorestframework. First make sure that djangoRestFramework is registered in the Settings file application.

The installation

pip install djangorestframework-jwtCopy the code

configuration

INSTALLED_APPS = [
    ...
    'djangorestframework'. ]# certification
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication'.'rest_framework.authentication.SessionAuthentication'.'rest_framework.authentication.BasicAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), # JWT_EXPIRATION_DELTA specifies the expiration date of the token
}Copy the code

routing

from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [
    # JWT complete login
    url(r'^authorizations/$', obtain_jwt_token),
]Copy the code

The default JWT only returns a token value to the front end. We also need to override the jwt_response_payload_handler method to return the front end user and id and specify that in the configuration file.

def jwt_response_payload_handler(token, user=None, request=None):
    "" Custom JWT authentication success return data ""
    return {
        'token': token,
        'id': user.id,
        'username': user.username
    }Copy the code

The configuration is updated to:

# JWT configuration
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'utils.jwt_response.jwt_response_payload_handler',}Copy the code

Using token values generated by DjangorestFramework – JWT, the front-end can be stored in the browser’s Storage using JS.



advantages

  • Json’s generality. As a result, JWT can be cross language support, like JAVA, JavaScript, NodeJS, many languages such as PHP can be used;
  • Because of the payload part, JWT can store non-sensitive information in itself that is necessary for other business logic.
  • Easy to transport. JWT is very simple in structure and has a small byte footprint, so it is very easy to transport;
  • It does not need to store session information on the server, so it is easy to apply extensions.

Safety related

  • Sensitive information should not be stored in the Payload part of the JWT because it is the part that the client can decrypt.
  • Protect the secret private key, which is very important.
  • If yes, use HTTPS.