The principle of generating Token by JWT and the principle of public key and private key encryption and decryption

Keywords: jwt

Opening:

         There are many ways to implement tokens. This article introduces the tokens generated by Json Web Token(JWT). What are the benefits of the tokens generated by JWT?

  • It has high security, plus key encryption, and supports a variety of algorithms.
  • The information carried is user-defined, and you can verify whether the token has expired.
  • The verification information can be saved by the front end, and the back end does not need to consume memory for saving token s.

         Little knowledge: Base64 is a kind of code, that is, it can be translated back to its original appearance. It is not an encryption process.

What is JWT?

         JSON Web Token is called JWT for short.
         A JWT is actually a string, which consists of three parts: header, payload and signature.
         The token generated by JWT is like this

eyJpc3MiOiJKb2huI.eyJpc3MiOiJ.Kb2huIFd1IEp

         The generated token is 3 segments, connected with. Here's an explanation. Among them, the header and load of the first two segments are encoded through Base64, and the last segment is the string after connecting the first two segments and encrypting them through the corresponding encryption algorithm (here HS256).

head

         It is used to describe the most basic information about the JWT, such as its type and the algorithm used for signature. This can also be represented as a JSON object.
         The header is a JSON object, which is generally encoded by Base64URL. It carries two parts of information and stores some declaration information, such as: what encryption and what encoding to use [function: specify the signature used by JWT]

  1. Declare the type type, indicating the type of the token. JWT tokens are uniformly written as JWT
  2. The algorithm alg for declaring encryption usually uses HMAC SHA256 directly or RSA. It supports many algorithms (HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384)

Detailed explanation of encryption algorithm, click here
         HS starts with HMAC-SHAX. It uses HAMC to hash the SHA digest algorithm with salt (secret key).
The other three are the results obtained by encrypting the signature with asymmetric algorithm and summarizing the results.


For example:

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

load

         In fact, it is user-defined data, which generally stores user Id, expiration time and other information. That is the core of JWT, because these data are the credentials that make the backend know which user has logged in. Moreover, these data are stored in the token and carried by the front end, so the back end hardly needs to save any data.
         Note: no sensitive data should be added to the load, because it can be decoded directly through Base64.
         Payload, also known as message body, is a JSON object, which is generally encoded by Base64URL. It stores main useful information, such as login user name, login time, login expiration time, and some user-defined information [function: specify JWT request data]
         The valid information consists of three parts: the declaration registered in the standard, the public declaration and the private declaration
         1, Declaration registered in the standard:

  1.   iss(issuer): jwt issuer
  2.   Sub (subject): the user JWT is aimed at, the login user name, etc
  3.   aud(audience): jwt receiver
  4.   Exp (expiration time): the expiration time of JWT, which must be greater than the issuance time
  5.   nbf(Not Before): effective time, which is defined before
  6.   IAT (issuedat): issuing time of JWT
  7.   JTI (JWT ID): the unique identity of JWT, which is mainly used as a one-time token to avoid replay attacks

         2, Public declaration: any information can be added to the public declaration. Generally, the user's relevant information or other necessary information required by the business can be added, but it is not recommended to add sensitive information, because this part can be decrypted at the client
         3, Private declaration: 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:

{
  "uid": "xxxxidid",  //User id
  "exp": "12121212"  //Expiration time
}

autograph

         Signature is actually:

  1. The header and load are respectively base64 encrypted and connected with. And then the first two token s of xxx.xx are formed.
  2. The last token is formed by adding a key to the first two paragraphs and encrypting them with HS256 algorithm or other algorithms.

          Therefore, the token3 segment is formed at the signature.

         Main purpose: after receiving the JWT, the server application will first re sign the contents of the header and load with the same algorithm. If the server application signs the header and load with the same method again and finds that the signature calculated by itself is different from the received signature, it means that the content of the Token has been moved by others, and we should reject the Token, Returns an HTTP 401 Unauthorized response.

  1. How to use the io.jsonwebtoken package

  pom.xml imported jar package

<dependencies>
    <!-- Base64 Encryption package, if added Tomcat The running environment does not need to be imported -->
    <!-- <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency> -->
    <!-- jjwt package -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.6.0</version>
    </dependency>
    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>
</dependencies>

User entity

package com.jjwt.entity;
 
/**
 * @ClassName: User
 * @Description: User entity
 */
public class User { 
    private int id;
    private String username;
    private String password;
 
    public User() {
        super();
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }
 
}

JjwtUtil class

package com.jwt.utils; 

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; 
import org.apache.tomcat.util.codec.binary.Base64; 
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm; 
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
 
// Using the io.jsonwebtoken package
public class JjwtUtil {
 
    // jti: unique identity of jwt
    public static final String JWT_ID = UUID.randomUUID().toString();
 
    // Encrypted ciphertext, private key
    public static final String JWT_SECRET = "jiamimiwen";
 
    // Expiration time in milliseconds
    public static final int EXPIRE_TIME = 60 * 60 * 1000; // An hour
//     public static final long EXPIRE_TIME = 7 * 24 * 3600 * 1000; //  A week
 
    // Generate encryption key from string
    public static SecretKey generalKey() {
        // Local password decoding
        byte[] encodedKey = Base64.decodeBase64(JWT_SECRET);
        // According to the given byte array, use AES encryption algorithm to construct a key
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
 
    // Create jwt
    public static String createJWT(String issuer, String audience, String subject) throws Exception {
        // Set header information
//        Map<String, Object> header = new HashMap<String, Object>();
//        header.put("typ", "JWT");
//        header.put("alg", "HS256");
        // or
        // The signature algorithm used when specifying the header signature has been encapsulated by jjwt. Only {"alg":"HS256"}
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        // Create a payload private statement (add it according to specific business needs. If you want to use this for verification, you generally need to communicate the verification method with the jwt receiver in advance)
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", "admin");
        claims.put("password", "010203");
        // jti user id, for example: 20da39f8-b74e-4a9b-9a0f-a39f1f73fe64
        String jwtId = JWT_ID;
        // Time when JWT was generated
        long nowTime = System.currentTimeMillis();
        Date issuedAt = new Date(nowTime);
        // The secret key used when generating the signature. Remember that this secret key cannot be exposed. It is the private key of your server and should not be revealed in any scenario. Once the client knows this secret, it means that the client can issue jwt it by itself
        SecretKey key = generalKey();
        // Add various standard and private declarations to the payload
        JwtBuilder builder = Jwts.builder() // Represents a new JwtBuilder and sets the body of jwt
//                . setHeader(header) / / set header information
                .setClaims(claims) // If there is a private declaration, you must first set the private declaration you created. This is to assign a value to the builder's claim. Once it is written after the assignment of the standard declaration, it overwrites those standard declarations
                .setId(jwtId) // jti(JWT ID): the unique identity of jwt, which can be set as a non duplicate value according to business needs. It is mainly used as a one-time token to avoid replay attacks
                .setIssuedAt(issuedAt) // iat(issuedAt): issuing time of jwt
                .setIssuer(issuer) // iss(issuer): jwt issuer
                .setSubject(subject) // sub(subject): the user for which jwt is targeted, including the login user name, a json format string, which can store userid, roldid, etc. as the unique flag of the user
                .signWith(signatureAlgorithm, key); // Set the signature, using the signature algorithm and the secret key used for the signature
        // Set expiration time
        long expTime = EXPIRE_TIME;
        if (expTime >= 0) {
            long exp = nowTime + expTime;
            builder.setExpiration(new Date(exp));
        }
        // Set jwt recipient
        if (audience == null || "".equals(audience)) {
            builder.setAudience("Tom");
        } else {
            builder.setAudience(audience);
        }
        return builder.compact();
    }
 
    // Decrypt jwt
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey key = generalKey(); // The signature secret key as like as two peas of the generated signature.
        Claims claims = Jwts.parser() // Get DefaultJwtParser
                .setSigningKey(key) // Set secret key for signature
                .parseClaimsJws(jwt).getBody(); // Set jwt to resolve
        return claims;
    }
 
}

TestJjwt test class

package com.jwt.test; 

import java.text.SimpleDateFormat; 
import com.alibaba.fastjson.JSON;
import com.jwt.entity.User;
import com.jwt.utils.JjwtUtil; 
import io.jsonwebtoken.Claims;
 
// Using the io.jsonwebtoken package
public class TestJjwt {
 
    public static void main(String[] args) {
        User user = new User();
        user.setId(10);
        user.setUsername("Zhang San");
        user.setPassword("123123");
        // The user jwt is aimed at, including the login user name, etc
        String subject = JSON.toJSONString(user);
        try {
            // "Jack" is the issuer of jwt and "Li Si" is the receiver of jwt
            String jwt = JjwtUtil.createJWT("Jack", "Li Si", subject);
            System.out.println("JWT: " + jwt);
            System.out.println("JWT Length:" + jwt.length());
            System.out.println("\njwt Among the three components payload Partial decryption:");
            Claims c = JjwtUtil.parseJWT(jwt);
            System.out.println("jti user id: " + c.getId());
            System.out.println("iat Login time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getIssuedAt()));
            System.out.println("iss Issued by:" + c.getIssuer());
            System.out.println("sub User information list:" + c.getSubject());
            System.out.println("exp Expiration time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getExpiration()));
            System.out.println("aud recipient:" + c.getAudience());
            System.out.println("Login user name:" + c.get("username"));
            // or
            System.out.println("Login user name:" + c.get("username", String.class));
            System.out.println("Login password:" + c.get("password", String.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}

Printed results

JWT: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJpZFwiOjEwLFwicGFzc3dvcmRcIjpcIjEyMzEyM1wiLFwidXNlcm5hbWVcIjpcIuW8oOS4iVwifSIsImF1ZCI6IuadjuWbmyIsInBhc3N3b3JkIjoiMDEwMjAzIiwiaXNzIjoiSmFjayIsImV4cCI6MTU2NzUwOTYyMiwiaWF0IjoxNTY3NTA2MDIyLCJqdGkiOiJjYjkyMjlkMi1mMDRiLTQ2NmUtOGY4Ny1iMGM4OWU3YWQ5NDEiLCJ1c2VybmFtZSI6ImFkbWluIn0.UG7aVfmQO28bRTrCyD1u2C8pKYXONZ2FZ_R7aFYhJN0
JWT Length: 352
 
jwt Among the three components payload Partial decryption:
jti user id: cb9229d2-f04b-466e-8f87-b0c89e7ad941
iat Login time: 2019-09-03 18:20:22
iss Issued by: Jack
sub User information list:{"id":10,"password":"123123","username":"Zhang San"}
exp Expiration date: 2019-09-03 19:20:22
aud Receiver: Li Si
 Login user name: admin
 Login user name: admin
 Login password: 010203

2. How to use com.auth0 package

2.1 pom.xml file

<properties>
    <!-- Spring Version number -->
    <spring.version>5.1.5.RELEASE</spring.version>
</properties>
 
<dependencies>
    <!-- junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- spring core core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--spring bean bean Management of -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--spring context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--spring context support -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- spring web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- spring mvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- spring tx -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- spring jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- spring El expression -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- spring test -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!-- jwt My bag -->
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.5.0</version>
    </dependency>
    <!-- jjwt package -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.6.0</version>
    </dependency>
    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>
</dependencies>

The User entity uses the above

2.2 JWTInterceptor interceptor

package com.jwt.interceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; 
import com.jwt.utils.JWTUtil; 
import io.jsonwebtoken.Claims;
 
public class JWTInterceptor implements HandlerInterceptor {
    
    @Autowired
    private JWTUtil jWTUtil;
 
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e)
            throws Exception {
 
    }
 
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav)
            throws Exception {
 
    }
 
    // Block every request
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) {
        System.out.println("Start entering interceptor inspection jwt Does the head contain Authorization method!");
        // Get whether the token request header contains Authorization through the url
        String jwt = request.getHeader("Authorization");
        System.out.println(jwt);
        try {
            // Check whether the request header is empty
            if (jwt == null) {
                System.out.println("User is not logged in, authentication failed");
            } else {
                Claims c = jWTUtil.parseJWT(jwt);
                System.out.println("user[ " + c.get("username") + " ]Is already logged in");
                System.out.println("End entry interceptor inspection jwt Does the head contain Authorization method!");
                return true;
            }
            System.out.println("token Parsing error, validation failed");
            response.getWriter().write("Not logged in, please log in again");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
 
}

2.3 spring-context.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
 
    <!-- Enable annotation scanning, and scan all classes in the package to complete Bean The ability to create and automate dependency injection -->
    <context:component-scan base-package="com.jwt" />
 
    <!-- Enable annotation driven, start based on Spring MVC Add controller and method mapping to the container -->
    <mvc:annotation-driven />
 
    <!-- Interface cross domain configuration -->
    <mvc:cors>
        <!-- allowed-methods="*" Indicates that all requests are valid -->
        <mvc:mapping path="/**" allowed-origins="*"
            allowed-methods="*"
            allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
            allow-credentials="true" />
    </mvc:cors>
 
    <!-- Interceptor -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- Configure the path of interceptor, and any request will be intercepted -->
            <mvc:mapping path="/**" />
            <!-- Exclude the interception of the specified path user/dologin -->
            <mvc:exclude-mapping path="/user/dologin" />
            <!-- definition<mvc:interceptor>Element, which indicates that the request matching the specified path is intercepted -->
            <bean class="com.jwt.interceptor.JWTInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors> 
</beans>

2.4 web.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
 
    <servlet>
        <servlet-name>jwt</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>jwt</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping> 
</web-app>

2.5 JWTUtil class

package com.jwt.utils;
 
import java.util.Date; 
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; 
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Component; 
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier; 
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
 
/**
 * 
 * @ClassName: JWTUtil
 * @Description: Implement the encryption of user name and password, verify whether the token is correct, and obtain the user name
 * Algorithm algorithm = Algorithm.HMAC256(password) It is to encrypt the password and confuse it with the user name
 * When signing, you can specify the expiration time of the token through. withExpiresAt(date)
 * @param:
 */
@Component
public class JWTUtil {
 
    // Expiration time in milliseconds
    private static final long EXPIRE_TIME = 60 * 1000; // 1 minute
//     private static final long EXPIRE_TIME = 15 * 60 * 1000; // 15 minutes
 
    // Encrypted ciphertext, private key
    private static final String TOKEN_SECRET = "jiamimiwen";
    
    // Generate encryption key from string
    public SecretKey generalKey() {
        System.out.println("Enter encryption generated by string key method!");
        // Local password decoding
        byte[] encodedKey = Base64.decodeBase64(TOKEN_SECRET);
        // According to the given byte array, use AES encryption algorithm to construct a key
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
 
    // Generate signature
    public String sign(int id, String username, String password) {
        System.out.println("The signature generation method begins to execute!");
        try {
            // Sets the expiration time in milliseconds
            Date expTime = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            // Private key and encryption algorithm
            Algorithm algorithm = Algorithm.HMAC256(password); //Use the password entered by the user
//            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // The header information can be set or not. The header information jwt will be generated automatically
//            Map<String, Object> header = new HashMap<String, Object>();
//            header.put("typ", "JWT");
//            header.put("alg", "HS256");
            // or
            // header.put("Type", "JWT");
            //    header.put("alg", "HS256");
            // Time when JWT was generated
            Date issuedAt = new Date(System.currentTimeMillis());
            // Return token string
            System.out.println("The execution of the generated signature method has ended!");
            return JWT.create() // Represents a JWT for new, and sets the body of JWT
//                    . withHeader(header) / / set header information
                    .withClaim("id", id) // id of the user in the database
                    .withClaim("username", username) // User name entered by the front end
                    .withIssuedAt(issuedAt) // Issuing time of jwt
                    .withExpiresAt(expTime) // jwt expiration time
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 
     * @Title: verify
     * @Description: Verify whether the token is correct
     * @param: @param token secret key
     * @param: @param username Login name
     * @param: @param password password
     * @param: @return
     * @return: boolean
     * @throws
     */
    public boolean verify(String token, String username, String password) {
        System.out.println("Entry Inspection token Correct method!");
        try {
            Algorithm algorithm = Algorithm.HMAC256(password); //Use the password entered by the user
//            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
//            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    // Get login
    public String getUsername(String token) {
        System.out.println("Enter the method of obtaining login name!");
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    
    // Decrypt jwt
    public Claims parseJWT(String jwt) throws Exception {
        System.out.println("Enter decryption jwt method!");
        SecretKey key = generalKey(); // The signature secret key as like as two peas of the generated signature.
        Claims claims = Jwts.parser() // Get DefaultJwtParser
                .setSigningKey(key) // Set secret key for signature
                .parseClaimsJws(jwt).getBody(); // Set jwt to resolve
        return claims;
    }
 
}

2.6 UsersController layer

package com.jwt.controller;
 
import java.util.HashMap;
import java.util.Map; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; 
import com.jwt.entity.User;
import com.jwt.utils.JWTUtil;
 
@RestController
@RequestMapping("user")
public class UserController {
 
    @Autowired
    private JWTUtil jWTUtil;
 
    @PostMapping("dologin")
    public Map<String, Object> dologin(@RequestParam String username, @RequestParam String password) {
//    public Map<String, Object> dologin(@RequestBody User user) {
        System.out.println("dologin Method starts execution!");
        int id = 10;
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);
//        String username = user.getUsername();
//        String password = user.getPassword();
        Map<String, Object> map = new HashMap<String, Object>();
        if ("admin".equals(username) && "123456".equals(password)) {
            String token = jWTUtil.sign(id, username, password);
            if (token != null) {
                map.put("code", "200");
                map.put("message", "Authentication successful!");
                map.put("token", token);
                map.put("data", user);
                System.out.println("dologin Method end execution----Authentication succeeded!");
                return map;
            }
        } else {
            map.put("code", "000");
            map.put("message", "Authentication failed!");
            System.out.println("dologin Method end execution----Authentication failed!");
        }
        return map;
    }
 
    @GetMapping("list")
    public Map<String, Object> list() {
        System.out.println("list Method starts execution!");
        Map<String, Object> map = new HashMap<String, Object>();
        User user = new User();
        user.setId(1001);
        user.setUsername("Zhang San");
        user.setPassword("123123");
        map.put("users", user);
        System.out.println("list Method end execution!");
        return map;
    }
 
}

Original link: https://blog.csdn.net/weixin_42030357/article/details/95629924

Posted by geoffism on Wed, 13 Oct 2021 11:45:09 -0700