Detailed explanation of JSON web token (JWT) and Java project practice

Time:2020-9-19

Why do we use token

Token, a token, represents the right to perform certain operations, that is, our pass to perform certain operations.

1.1 a long time ago, what did we use for authentication?

We all know that HTTP is a stateless protocol: http has no memory for transaction processing and does not save the communication state between request and response.
Using HTTP protocol, whenever a new request is sent, a corresponding new response will be generated. The protocol itself does not retain all the previous request or response message information. This is to deal with a large number of transactions faster and ensure the scalability of the protocol, and designed the HTTP protocol to be so simple.

However, with the development of the web, the early stateless feature has brought a lot of inconvenience. For example, users log in to Sina Weibo and enter the home page after entering the user name and password on the login page. However, because HTTP is stateless, HTTP does not know whether the last HTTP request has passed the verification or not, let alone the specific information of the current user.

The simplest solution is to carry the user name and password in all requests. Although this is feasible, it greatly increases the burden of the server (for each request, it needs to be verified in the database), and the user has to enter the password once every page, which has no user experience.
Therefore, various authentication mechanisms are introduced

1.1.1 Cookie & session

Cookie is a small text file set by HTTP server and saved in browser. Its content is a series of key value pairs

Session is stored on the server side relative to the cookie stored in the browser

Cookie delivery process:

  • The browser sends a request to a URL
  • The corresponding server receives the HTTP request and generates the HTTP response to be sent to the browser
  • Add the set cookie field to the response header, and the value is the cookie to be set
  • The browser received an HTTP response from the server
  • If the browser finds the set cookie field in the response header, it will save the value of the field in memory or hard disk.
  • The next time an HTTP request is sent to the server, the cookie set by the server is appended to the field cookie of the HTTP request.
  • After receiving the HTTP request, the server will know that the user’s request has been processed if there is a cookie field in the request header.
  • Expired cookies will be deleted

Authentication process based on cookie session

  • User input login information
  • The server verifies whether the login information is correct. If it is correct, it creates a session for the user on the server side and stores the session in the database
  • The server will return the cookie with the sessionid to the client
  • After receiving the request from the server, the client sees the set cookie field in the response header and saves the cookie
  • The cookie will be carried in the next request. The server will match the sessionid with the one in the database. If it is valid, the request will be processed
  • If the user logs out, the session will be destroyed on both the client and server sides
1.1.2 disadvantages of cookie & session
  1. Since cookies and sessions need to be stored in browser memory and server memory, resource consumption will be large when the request increases
  2. If the browser blocks the cookie, it will cause a lot of trouble. We need to find a new way to use URL rewriting
  3. Poor support for distributed systems
  4. If the cookie is intercepted, users will be vulnerable to cross site request forgery attack.

1.2 token based authentication

The token does not need to store user information in the server, and the way of token transmission is not limited to cookie transmission.

When the user visits the server for the first time, the server generates a token through algorithm and encryption key. The token is sent to the client after Base64 encoding.

The client saves the token, and the next request takes the token. When the server receives the request, it will use the same algorithm to get the validation token. If it passes, it will continue to execute.

At this time, the server becomes stateless, which makes it easier to expand

Session is the session and token is the token.

Token solves the problem of poor scalability of session

2. JWT

2.1 JWT structure

A JWT is actually a string, which is composed of three parts. The header, payload and signature are linked in order with a dot (“.) in sequence: 1. Header, 2. Payload, 3. Signature.

  • Header (head)
  • Payload
  • Signature

Here is a JWT string:

eyJhbGciOiJIUzI1NiJ9.eyJleHBpcmVUaW1lIjoxNTg5MDE0MzA2OTU0LCJkZXB0Ijoi5Yas6KW_55Oc5ZywIiwidXNlcm5hbWUiOiLlpKfopb_nk5wifQ.QSv0FcvNheiA3FW6OEah7jJKG4SG0ver3q67F0980rY
2.1.1 header
eyJhbGciOiJIUzI1NiJ9

After decryption with Base64, we get the following results:

{"alg":"HS256"}
2.1.2 payload

The payload part is also a JSON object, which is used to store the actual data to be passed. JWT provides seven official fields for selection:

  • ISS (issuer): issuer
  • Exp (expiration time): expiration time
  • Subject: subject
  • Aud (audience): audience
  • NBF (not before): effective time
  • IAT (issued at): issuing time
  • JTI (JWT ID): number

You can also customize:

  • User name: watermelon

JWT is not encrypted by default and can be read by anyone, so don’t put secret information in this section.

2.1.3 signature

The signature part is the signature of the first two parts to prevent data tampering.
The first two parts are encrypted using the specified encryption algorithm and the server only secret.

2.1.4 splicing

After the signature is calculated, the header, payload and signature are combined into a string, and each part is separated by a dot (.) to generate a complete JWT token

2.2 several features of JWT

  • JWT is not encrypted by default, but can also be encrypted. After the original token is generated, it can be encrypted again with the key.
  • JWT can be used not only for authentication, but also for exchanging information. Effective use of JWT can reduce the number of times the server queries the database.
  • The biggest drawback of JWT is that because the server does not save the session state, it is unable to revoke a token or change the permissions of a token during use. That is, once the JWT is issued, it will remain valid until it expires, unless the server deploys additional logic.
  • JWT itself contains authentication information, once leaked, anyone can get all rights of the token. In order to reduce embezzlement, the validity period of JWT should be set short. For some important permissions, users should be authenticated again.
  • In order to reduce the embezzlement, JWT should not use the HTTP protocol, but use the HTTPS protocol.

3. Using JWT in Java

In this paper, jjwt is used to generate and decrypt JWT in Java environment

3.1 introduce jjwt Maven dependency

The latest version is 0.9.1

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

3.2 configure key

private static final String SALT = "0142add7c2664198863943f24bf4b8b9";

private static Key getKeyInstance() {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    String apiKey = DatatypeConverter.printBase64Binary(SALT.getBytes());
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    return signingKey;
}

3.3 generating token

public static String createJavaWebToken4JwtAuth(Map<String, Object> claims) {
    logger.info ("generated token is the beginning");
    String toekn = Jwts.builder().setClaims(claims).setExpiration(DateUtil.addSeconds(new Date(), 50))
            .signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
    logger.info (the generated token is: + toekn);
    return toekn;
}

The properties in the official payload are configured with corresponding API, and. Setexpiration is configured in( DateUtil.addSeconds (new Date(), 50))

3.4 getting the body part

public static Map<String, Object> verifyJavaWebToken(String jwt) {
    try {
        Map<String, Object> jwtClaims =
                Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwt).getBody();
        return jwtClaims;
    } catch (Exception e) {
        logger.info(e.getMessage());
        return null;
    }
}

When the current time exceeds the configured expiration time, an exception is thrown

3.5 validation method

public static boolean isTokenEffect(String jwt) {
    if (StringUtils.isEmpty(jwt)) {
        return false;
    }
    Map<String, Object> claims = verifyJavaWebToken(jwt);
    if (null == claims) {
        logger.info ("conversion of JWT failed! "";
        return false;
    }
    return true;
}

3.6 use

public static void main(String[] args)  {

    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put ("user name", "big watermelon");
    paramMap.put "Dept" ("winter watermelon field");
    String tokens = JwtUtil.createJavaWebToken4JwtAuth(paramMap);
    System.out.println(tokens);
    System.out.println(isTokenEffect(tokens));

}

This article jwtutil has submitted GitHub to my toolset ytooo util

My toolset includes common string processing, date processing, HTTP request encapsulation, file processing, request body encapsulation and so on

Welcome to

<dependency>
  <groupId>ml.ytooo</groupId>
  <artifactId>ytooo-util</artifactId>
  <version>3.6.5</version>
</dependency>

< font color =                    watermin

Recommended Today

On the theoretical basis of SRE

What is SRE? When I first got into contact with SRE, many people thought that it was a post with full stack capability in Google and could solve many problems independently. After in-depth exploration, it is found that SRE can solve many problems, but there are too many problems. It is difficult for a post […]