Explanation of JWT and use of JJWT

Keywords: Java jwt

1. What is JWT

JSON Web Token (JWT) is a lightweight authentication specification that allows us to use JWT to transfer safe and reliable information between users and servers. Its essence is a token. It is a compact URL security method, which is used to pass between the two sides of network communication.

2. Composition of JWT

A JWT is actually a string, which consists of three parts: header, payload and signature

2.1 Header

The header is used to describe the most basic information about the JWT, such as its type and the algorithm used for signature

The header can be represented as a JSON object

{"typ":"JWT","alg":"HS256"}

The header indicates that the signature algorithm is HS256 algorithm. We encode BASE64, and the encoded string is as follows:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

BASE64 is a representation of binary data based on 64 printable characters. Since the 6th power of 2 is equal to 64, every 6 bits are a unit corresponding to a printable character. Three bytes have 24 bits, corresponding to four BASE64 units, that is, three bytes need to be represented by four printable characters. JDK provides very convenient BASE64Encoder and BASE64Decoder, which can be used to complete BASE64 based encoding and decoding

2.2 payload

Load is the place where valid information is stored. These valid information includes three parts:

2.2.1 declaration registered in the standard (recommended but not mandatory)

iss: jwt Issuer
sub: jwt Target users
aud: receive jwt Party of
exp: jwt The expiration time of must be greater than the issuing time
nbf: Define the time before which the jwt Are not available.
iat: jwt Date of issue
jti: jwt The unique ID of the, which is mainly used as a one-time ID token,To avoid replay attacks.

2.2.2 public statements

Any information can be added to the public statement. Generally, the user's relevant information or other necessary information required by the business can be added. However, it is not recommended to add sensitive information because this part can be decrypted on the client

2.2.3 declaration of private ownership

Private declaration is a declaration jointly defined by providers and consumers. It is generally not recommended to store sensitive information, because base64 is symmetrically decrypted, which means that this part of information can be classified as plaintext information

For example, admin and name in the following example belong to self-defined claim. The difference between these claims and the claims specified in the JWT standard is: the claims specified in the JWT. After receiving the JWT, the receiver of the JWT knows how to verify the claims of these standards; private claims will not be verified unless the receiver is explicitly told to verify these claims and the verification rules

Define a payload:

{"sub":"1234567890","name":"John Doe","admin":true}

Then it is encrypted with base64 to obtain the second part of Jwt:

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9

2.3 visa

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

  • Header (after Base64)

  • Payload (after Base64)

  • secret

This part requires the use of base64 encrypted header and base64 encrypted payload. The string is connected, and then salt secret combination encryption is carried out through the encryption method declared in the header, and then the third part of jwt is formed:

TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Connect these three parts into a complete string with. To form the final jwt:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Note: secret is saved on the server side, and jwt issuance is also generated on the server side. Secret is used for jwt issuance and jwt verification, so secret is the private key of your server side and should not be revealed in any scenario. Once the client knows this secret, it means that the client can sign jwt it

3. Introduction to jjwt

JJWT is a Java library that provides end-to-end JWT creation and validation

Official documents: https://github.com/jwtk/jjwt

4. Use of jjwt

<!--authentication -->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;

public class TestJWT {

    public static void main(String[] args) {
        testCreateJWT();
        testParseJWT();
    }

    public static void testCreateJWT() {
        JwtBuilder builder = Jwts.builder()
                .setId("404")                   // Set unique number
                .setSubject("Xing Libao")            // The setting theme can be JSON data
                .setIssuedAt(new Date())        // Set issue date
                // . setExpiration(new Date()) / / set expiration time
                // Set the signature to use HS256 algorithm and set the secretkey (string)
                .signWith(SignatureAlgorithm.HS256, "LICHUN");

        HashMap<String, Object> userInfo = new HashMap<>();
        userInfo.put("name","When can dead trees spring");
        userInfo.put("age", "21");
        builder.addClaims(userInfo);

        System.out.println(builder.compact());
    }

    public static void testParseJWT() {
        String str = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0MDQiLCJzdWIiOiLpgqLnq4vosbkiLCJpYXQiOjE2MzA2ODAzNTMsImV4cCI6MTYzMDY4MDM1MywibmFtZSI6Iuaer-acqOS9leaXpeWPr-mAouaYpSIsImFnZSI6IjIxIn0.59i5xfLz9A-wTOJI9KxkF7zqp4zsLEWRC5DYlcy_Akc";
        Claims claims = Jwts.parser()
                .setSigningKey("LICHUN")
                .parseClaimsJws(str)
                .getBody();
        System.out.println(claims);
    }
}

Posted by grayson on Fri, 03 Sep 2021 17:35:59 -0700