A comprehensive guide to JWT

What is JWT?

JWT (JSON Web Token) is an open standard, and the standard number is RFC7591. Used to securely transfer information between different entities. It is based on JSON encoded tokens.

The composition of JWT

JWT consists of three parts: Header, Payload and Signature.

  1. The header contains the token type (typ) and the signature algorithm used (alg), which is usually represented by Base64 encoding. Examples are as follows:
{
  "alg": "HS256",
  "typ": "JWT"
}
  1. Payload is the main information storage part of the token and contains various claims to represent information about the entity (user, device, or other subject) and other supplementary data. The payload can contain standard declarations (for example: iss, sub, exp, nbf, iat, aud, etc.) or custom declarations. The payload is also Base64 encoded and transmitted in the token. Examples are as follows:
{
  "sub": "myapp",
  "name": "oscar",
  "role": "admin"
}
  1. A signature is a hash value that uses a key to sign the header and payload to ensure that the token cannot be tampered with. The signature is typically generated using the algorithm (e.g.: HMAC, RSA, etc.) and key specified in the header, and is appended to the end of the token as a string. Signature verification can be used to verify the integrity and authenticity of the token.

Looking at the process of generating JWT in Java language, the steps are as follows:

  1. Generate the Base64 encoded string of the header
String header = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
String encodedHeader = Base64.getEncoder().encodeToString(header.getBytes());
  1. Generate the Base64 encoding string of the vector
		String payload = "{\"sub\":\"myapp\",\"name\":\"oscar\"}";
		String encodedPayload = Base64.getEncoder().encodeToString(payload.getBytes());
  1. After using the dot .to connect the header and the carrier, use the signature algorithm to sign, and append the signed content to the end of the entire string.
		Key secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
		String concatenated = encodedHeader + '.' + encodedPayload;

		Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
		sha256_HMAC.init(secretKey);
		byte[] signature = sha256_HMAC.doFinal(concatenated.getBytes("utf-8"));
		String compact = concatenated + '.' + Base64.getEncoder().encodeToString(signature);

The complete string obtained after generation is as follows:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJteWFwcCIsIm5hbWUiOiJvc2NhciJ9.5z6NoiF7MR999wOPn2NU6HnyPODx66qm5yRT+n8pNHs=

The content obtained after decoding through https://base64.us/ is as follows:
Insert image description here

As can be seen from the above, the JWT token is a string.

The role of JWT

JWT is suitable for transmitting authentication and authorization information in network requests, and is often used to build stateless authentication and access control mechanisms. After the client receives the token, it can verify its validity by decoding and validating the token, and use the information in it for authorization and authentication.

To summarize, a JWT is a security token encoded in JSON, consisting of a header, payload, and signature components that can be used to pass information between entities and verify identity. It provides a simple, extensible, and self-contained mechanism for handling authentication and authorization related tasks.
JWT is also often used for single sign-on, that is, after the user logs in to system A, a token is generated, and then the user brings this token when accessing other systems, and then can access systems B, C, D, etc.

JWT advantages and disadvantages

  1. Based on JSON, easy to parse
  2. Rich content can be defined in tokens, easy to extend
  3. Anti-tampering and high security through asymmetric encryption and digital signatures
  4. Resource services can use JWT to complete authorization without relying on the authorization server.

shortcoming:

  • The JWT token is longer and takes up more storage space.

Encryption and decryption of JWT

Encryption and decryption of JWT usually involves the following three steps:

  1. Create JWT:
    Creating JWT requires preparing three parts: Header, Payload and Signature. When creating a JWT, first Base64 encode the header and payload, and concatenate the two encoded strings with dots to form the first part of the JWT. Then, use the key and the specified signature algorithm to sign the previous string, generate a signature string, and connect it with the previous string with a dot to form the final form of JWT.

  2. Verify JWT:
    The process of verifying JWT usually includes the following steps: First, Base64 decode the header and payload parts of the JWT to extract the information they contain. Next, a signature is calculated on the header and payload parts using the same algorithm and key used to create the JWT. Finally, the calculated signature string is compared to the signature part in the JWT. If the two are equal, it means that the JWT has not been tampered with and can be trusted.

  3. Decode the JWT:
    If you need to view the data contained in the JWT, you can Base64 decode the first part of the JWT to get the header and payload information. The decoded result is usually a string in JSON format, which can be converted into an object through the corresponding JSON parsing library.

It should be noted that the header and payload information in the JWT are not encrypted, only Base64 encoded. Therefore, this information can be easily obtained. In order to protect the confidentiality of the data, the payload part is usually encrypted using an encryption algorithm, that is, it is converted into JWE (JSON Web Encryption) format. JWE provides a standardized encryption method to protect sensitive information in JWT. Encrypted JWE includes header, key and encrypted ciphertext, etc., which need to be decrypted using the corresponding algorithm and key.

In general, JWT encryption and decryption usually involves the steps of creating the JWT, validating the JWT, and decoding the JWT. Among them, verifying JWT can be used to verify whether the JWT has been tampered with to ensure the integrity and credibility of the JWT. Encrypting the payload part can protect the sensitive information in the JWT and improve the confidentiality of the JWT.



おすすめ

転載: blog.csdn.net/oscar999/article/details/132706309
おすすめ