“This is the 14th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

What is Jwt?

Summary:

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.

What can Jwt do?

Scenario: Can be used for cross-domain authentication.

The traditional authentication process is as follows:

  1. The user sends the user name and password to the server.
  2. After authenticating the server, relevant data (such as user role, login time, etc.) will be saved in the current session.
  3. The server returns the session_ID to the user, and the session information is written to the user’s Cookie.
  4. Each subsequent request from the user will be passed to the server by fetching the session_ID in the Cookie.
  5. The server receives the session_ID and compares the previously saved data to confirm the user’s identity.

Disadvantages: This scheme will gradually increase the load of the server, and cookies stored in the client are easy to be intercepted and forged by masters, resulting in information security problems.

Compared with the traditional solution of session broadcast and stored in cookies, Jwt is more flexible to save data through the client, while the server does not need to save session data, and its own design can effectively prevent information from being forged illegally.

How is Jwt used?

1. First look at the composition of Jwt

Typically, a JWT looks like this:

The object is a long string separated into three substrings by the “.” delimiter.

Each substring represents a functional block with three parts: the JWT header, the payload, and the signature

JWT header: The JWT header part is a JSON object that describes the JWT metadata, usually as follows.

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

In the above code, the ALG attribute represents the algorithm used for the signature, which defaults to HMAC SHA256 (written as HS256); The TYp attribute indicates the type of the token, and the JWT token is written as JWT. Finally, the above JSON object is converted into a string for saving using the Base64 URL algorithm.

Payload: The payload part, which is the body content part of the JWT, is also a JSON object that contains the data to be passed. JWT specifies seven default fields to choose from. (Both optional Settings)

Iss: issuer exp: expiration time sub: subject aud: user NBF: unavailable before this time IAT: release time JTI: JWT ID Identifies the JWTCopy the code

In addition to the default fields, we can also customize private fields, as shown in the following example:

    {
      "sub": "123456",
      "name": "mingru",
      "acl": true
    }
Copy the code

Please note that JWT is unencrypted by default and anyone can read its contents, so do not build private information fields and store confidential information to prevent disclosure.

JSON objects are also converted to strings using the Base64 URL algorithm.

Signature hash

  1. The signature hash part is used to sign the above two parts of data and generate the hash through the specified algorithm to ensure that the data will not be tampered with.

  2. First, you need to specify a secret. This password is only stored on the server and cannot be disclosed to users. Then, the signature algorithm specified in the Jwt header (HMAC SHA256 by default) is used to generate the signature according to the following formula.

        HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(claims), secret)
    Copy the code
  3. After calculating the signature hash, the JWT header, payload, and three parts of the signature hash are combined into a string, each part separated by a “.” to form the entire JWT object.

Base64URL algorithm

  1. As mentioned earlier, both the JWT header and payload serialization algorithms use Base64URL. The algorithm is similar to the common Base64 algorithm, but slightly different.
  2. JWT as a token can be placed in a URL (for example index/? Token = XXX). The three characters used in Base64 are “+”, “/” and “=”. Because they have special meanings in urls, they are replaced in Base64URL: “=” is removed, “+” is replaced with “-“, and “/” is replaced with “_”. This is the Base64URL algorithm.

2. General working process of Jwt

  1. After the user authenticates with the server, a JSON object is generated and sent back to the user, and later, when the user communicates with the server, the client sends back the JSON object in the request.
  2. The server only relies on this JSON object to identify the user. To prevent users from tampering with data, the server adds signatures when objects are generated. When the user accesses other services in the same system again, a token string will be carried in the request header. The user’s identity is verified by parsing the token and the previous legal comparison to check whether it has been modified.

The server does not store any session data, meaning the server becomes stateless, making it easier to scale.

3. How to prevent the user information (payload) from being obtained and modified by the expert?

HMACSHA256(base64UrlEncode(header) + “.” + base64UrlEncode(Claims), secret); Each data volume to generate the signature of the hash are unique, and when you do get to the user’s information, although you can at least one of the data information, but if you want to modify illegally, it is conceivable that a validation token value generated to will produce change, so the server will to judge the visit, Prevents it from continuing.

Jwt token string generation code

<dependency> <groupId> IO. Jsonwebtoken </groupId> <artifactId> JJWT </artifactId> </dependency>Copy the code
Public class JwtUtils {private static final String SIGN="@das$25*j^"; private static final String SIGN="@das$25*j^"; Public static String getToken(Map<String,String> Map){// Set token expiration time Calendar instance = Calendar.getInstance(); instance.add(Calendar.DATE,7); JWTCreator.Builder builder = JWT.create(); map.forEach((k,v)->{ builder.withClaim(k,v); }); String token = Builder.withexpiresat (instance.getTime()) // Specify expiration time.sign (algorithm.hmac256 (sign)); String token = Builder.withexpiresat (instance.getTime()) // Specify expiration time. // Specify the encryption algorithm return token; }}Copy the code

Verify valid code

Public static DecodedJWT verify(String token){return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token); }Copy the code

End of story! Hope this article has been helpful…