An article about the principles and practical applications of JWT

Table of contents

1. Introduction

1.1.What is JWT

2. Structure

3. Use of Jwt tool classes

3.1. Dependencies

3.2.Tools

3.3.Filter

3.4.Controller

3.5.Configuration

3.6. Test class

Used to generate JWT 

Parse Jwt

Copy jwt and delay for 30 minutes

Test the validity time of JWT

 Test parsing of expired JWT

4. Application

              That’s it for today, I hope I can help you! !


1. Introduction

1.1.What is JWT

JWT refers toJSON Web Token, which is a security standard for transmitting information on the network. JWT consists of three parts: Header, Payload and Signature. The header contains information about the token type and the encryption algorithm used. The payload contains the data to be transferred. The signature is used to verify the authenticity of the token.

The workflow of a JWT usually looks like this:When a user authenticates, the server generates a JWT and returns it to the user in the response. The user stores the JWT locally for use in future requests. Every time a user sends a request to the server, a JWT needs to be included in the request. The server verifies the JWT's signature using the secret key to ensure its authenticity, and processes the request based on the information in the payload.

JWT has the following advantages:

  1. Stateless:The server does not need to store session information in the database, only verification in JWT.
  2. Scalability:JWT payloads can store any amount of data.
  3. Security:JWT contains a signature to prevent tampering or forgery.

JWT provides a secure and reliable way to transfer information between different systems and enables stateless authentication.

The usage process of JWT is as follows:

When the user logs in, the username and password are sent to the backend.

The backend validates the username and password, and if the validation passes, generates a JWT and returns it to the frontend.

The front end saves the JWT locally, generally using the browser's local storage (localStorage or sessionStorage) or HTTP Only cookies.

When the front end needs to access resources that require authentication, JWT is added to the request header and sent to the back end.

The backend verifies the legality of the JWT, including verifying the signature, validity period, etc. If the verification passes, the requested resource is returned.

The working principle of JWT can be briefly summarized as: authentication, issuance and verification.

1. Authentication: The user provides a valid username and password for authentication when logging in. The server verifies the user's identity and generates a JWT as the user's identity credential.
2. Issuance: The server generates a JWT based on the user's identity information and other related information (such as roles, permissions, etc.), and uses the key to sign the JWT. The signature is to ensure the integrity and authenticity of the JWT and prevent it from being tampered with.
3. Verification: The user sends JWT as an identity credential to the server in subsequent requests. After the server receives the request, it will verify the signature and validity period of the JWT. If the verification is passed, the server will determine the user's identity and permissions based on the information in the JWT, and then return the corresponding resources or perform the corresponding operations.

The specific workflow is as follows:

1. Users provide username and password for authentication when logging in.

2. The server verifies the user's identity and generates a JWT. JWT consists of three parts: Header, Payload and Signature.

   - Header: Contains information such as the JWT type (typ) and signature algorithm (alg).
   - Payload: Contains the user's identity information and other related information, such as user ID, roles, permissions, etc. The payload can also contain some customized information, such as expiration time (exp), etc.
   - Signature: A signature generated by encrypting the header, payload and server's key, used to verify the integrity and authenticity of the JWT.

3. The server returns the generated JWT to the user.

4. The user adds JWT as the identity credential to the request header in subsequent requests and sends it to the server. Usually, JWT is placed in the Bearer field of the Authorization header, such as: Authorization: Bearer <JWT>.

5. After the server receives the request, it parses the JWT and verifies its signature and validity period. If the verification is passed, the server can determine the user's identity and permissions based on the information in the JWT, and return the corresponding resources or perform the corresponding operations.

Note: JWT is stateless and the server does not need to save any state information. Each request includes authentication information, and the server can confirm the user's identity by verifying the signature and validity of the JWT. This can reduce the load on the server and is suitable for distributed systems and high-concurrency environments.

2. Structure

JWT (JSON Web Token) is an open standard (RFC 7519). It consists of three parts: header (Header), payload (Payload) and signature (Signature).

1. Header (Header): The header of JWT is a JSON object used to describe the metadata of JWT, such as Card type (typ) and signature algorithm (alg). Typically, the header will contain the following information:

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

  - alg:Specified name arithmetic, common usageHMAC SHA256 (HS256)sum a>RSA SHA256 (RS256) etc.
   - typ: Specified order type, general JWT.

  The header needs to be Base64 encoded as JWT The first part.

 

2. Payload (Payload): The payload of JWT is the part that stores the actual data and is also a JSON object. It contains a number of claims (claims) that describe the token's information. Common statements include:

   - iss (Issuer): The issuer of the token.
   - sub (Subject): The user the token is for.
   - aud (Audience): The recipient of the token.
   - exp (Expiration Time): The expiration time of the token.
   - nbf (Not Before): The validity time of the token.
   - iat (Issued At): The issuance time of the token.  - jti (JWT ID): The unique identifier of the token.
 

Example:

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

  The payload also needs to be Base64 encoded as the second part of the JWT.

3. Signature (Signature): The signature of JWT is a string composed of header, payload and key, used for verification Integrity and authenticity of JWT. How the signature is generated depends on the specified signature algorithm.

   - ForHMAC SHA256, the signature is generated as: HMACSHA256(base64UrlEncode(header)< /span>. base64UrlEncode(payload), privateKey)+ "." + RSASHA256(base64UrlEncode (header) , the signature is generated as: RSA SHA256    - For . base64UrlEncode(payload), secret) + "." +

 The generated signature will serve as the third part of the JWT.

Finally, the Base64 encoded header, payload and signature are connected with dots to form the final < a i=3>JWT

base64UrlEncode(header) + "." + base64UrlEncode(payload) + "." + signature

Structure example of JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibm

FtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwp

MeJf36POk6yJV_adQssw5c

It should be noted that, The information in JWT is passed through Base64encoding, although the original content can be obtained through Base64 decoding, it cannot be modified< a i=8>JWT because the signature verifies the integrity and authenticity of the JWT.

3. Use of Jwt tool classes

3.1. Dependencies

Import dependencies in the backend project:

In the properties configuration tag 

<jwt.version>0.9.1</jwt.version>
<java.jwt.version>3.4.0</java.jwt.version>

 In the dependencies configuration tag 

<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt</artifactId>
  <version>${jwt.version}</version>
</dependency>
<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>${java.jwt.version}</version>
</dependency>

3.2.Tools

Create tool class in the background: CorsFilter

package com.junlinyi.ssm.util;
 
import java.io.IOException;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * 配置tomcat允许跨域访问
 * 
 * @author Administrator
 *
 */
public class CorsFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
		HttpServletRequest req = (HttpServletRequest) servletRequest;
		// Access-Control-Allow-Origin就是我们需要设置的域名
		// Access-Control-Allow-Headers跨域允许包含的头。
		// Access-Control-Allow-Methods是允许的请求方式
		httpResponse.setHeader("Access-Control-Allow-Origin", "*");// *,任何域名
		httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
		
		//允许客户端发一个新的请求头jwt
		httpResponse.setHeader("Access-Control-Allow-Headers","responseType,Origin,X-Requested-With, Content-Type, Accept, jwt");
		//允许客户端处理一个新的响应头jwt
		httpResponse.setHeader("Access-Control-Expose-Headers", "jwt,Content-Disposition");
		
		//httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
		//httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
		
		// axios的ajax会发两次请求,第一次提交方式为:option,直接返回即可
		if ("OPTIONS".equals(req.getMethod())) {
			return;
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}
	@Override
	public void destroy() {
 
	}
}

3.3.Filter

Create filters in the background: JwtFilter & JwtUtils

 JwtFilter : 

package com.junlinyi.ssm.jwt;
 
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import io.jsonwebtoken.Claims;
 
/**
 * * JWT验证过滤器,配置顺序 :CorsFilter-->JwtFilter-->struts2中央控制器
 * 
 * @author Administrator
 *
 */
 
public class JwtFilter implements Filter {
 
	// 排除的URL,一般为登陆的URL(请改成自己登陆的URL)
	private static String EXCLUDE = "^/user/userLogin?.*$";
 
	private static Pattern PATTERN = Pattern.compile(EXCLUDE);
 
	private boolean OFF = false;// true关闭jwt令牌验证功能
 
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
 
	@Override
	public void destroy() {
	}
 
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//获取当前请求路径。只有登录的请求路径不进行校验之外,其他的URL请求路径必须进行JWT令牌校验
		//http://localhost:8080/ssh2/bookAction_queryBookPager.action
		//req.getServletPath()==/bookAction_queryBookPager.action
		String path = req.getServletPath();
		if (OFF || isExcludeUrl(path)) {// 登陆直接放行
				chain.doFilter(request, response);
				return;
		}
 
		// 从客户端请求头中获得令牌并验证
		//token=头.载荷.签名
		String jwt = req.getHeader(JwtUtils.JWT_HEADER_KEY);
		Claims claims = this.validateJwtToken(jwt);
		//在这里请各位大哥大姐从JWT令牌中提取payload中的声明部分
		//从声明部分中获取私有声明
		//获取私有声明中的User对象 -> Modules
		Boolean flag=false;
		if (null == claims) {
			// resp.setCharacterEncoding("UTF-8");
			resp.sendError(403, "JWT令牌已过期或已失效");
			return;
		} else {
			
			//1.获取已经解析后的payload(私有声明)
			//2.从私有声明中当前用户所对应的权限集合List<String>或者List<Module>
			//3.循环权限(Module[id,url])
			// OK,放行请求 chain.doFilter(request, response);
			// NO,发送错误信息的JSON
			// ObjectMapper mapper=new ObjectMapper()
			// mapper.writeValue(response.getOutputStream(),json)
			
			String newJwt = JwtUtils.copyJwt(jwt, JwtUtils.JWT_WEB_TTL);
			resp.setHeader(JwtUtils.JWT_HEADER_KEY, newJwt);
			chain.doFilter(request, response);
		}
	}
 
	/**
	 * 验证jwt令牌,验证通过返回声明(包括公有和私有),返回null则表示验证失败
	 */
	private Claims validateJwtToken(String jwt) {
		Claims claims = null;
		try {
			if (null != jwt) {
				//该解析方法会验证:1)是否过期 2)签名是否成功
				claims = JwtUtils.parseJwt(jwt);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return claims;
	}
 
	/**
	 * 是否为排除的URL
	 * 
	 * @param path
	 * @return
	 */
	private boolean isExcludeUrl(String path) {
		Matcher matcher = PATTERN.matcher(path);
		return matcher.matches();
	}
 
	// public static void main(String[] args) {
	// String path = "/sys/userAction_doLogin.action?username=zs&password=123";
	// Matcher matcher = PATTERN.matcher(path);
	// boolean b = matcher.matches();
	// System.out.println(b);
	// }
 
}

 JwtUtils : 

package com.junlinyi.ssm.jwt;
 
import java.util.Date;
import java.util.Map;
import java.util.UUID;
 
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
 
import org.apache.commons.codec.binary.Base64;
 
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
 
/**
 * JWT验证过滤器:配置顺序 CorsFilte->JwtUtilsr-->StrutsPrepareAndExecuteFilter
 *
 */
public class JwtUtils {
	/**
	 * JWT_WEB_TTL:WEBAPP应用中token的有效时间,默认30分钟
	 */
	public static final long JWT_WEB_TTL = 30 * 60 * 1000;
 
	/**
	 * 将jwt令牌保存到header中的key
	 */
	public static final String JWT_HEADER_KEY = "jwt";
 
	// 指定签名的时候使用的签名算法,也就是header那部分,jwt已经将这部分内容封装好了。
	private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256;
	private static final String JWT_SECRET = "f356cdce935c42328ad2001d7e9552a3";// JWT密匙
	private static final SecretKey JWT_KEY;// 使用JWT密匙生成的加密key
 
	static {
		byte[] encodedKey = Base64.decodeBase64(JWT_SECRET);
		JWT_KEY = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
	}
 
	private JwtUtils() {
	}
 
	/**
	 * 解密jwt,获得所有声明(包括标准和私有声明)
	 * 
	 * @param jwt
	 * @return
	 * @throws Exception
	 */
	public static Claims parseJwt(String jwt) {
		Claims claims = Jwts.parser()
				.setSigningKey(JWT_KEY)
				.parseClaimsJws(jwt)
				.getBody();
		return claims;
	}
 
	/**
	 * 创建JWT令牌,签发时间为当前时间
	 * 
	 * @param claims
	 *            创建payload的私有声明(根据特定的业务需要添加,如果要拿这个做验证,一般是需要和jwt的接收方提前沟通好验证方式的)
	 * @param ttlMillis
	 *            JWT的有效时间(单位毫秒),当前时间+有效时间=过期时间
	 * @return jwt令牌
	 */
	public static String createJwt(Map<String, Object> claims, 
			long ttlMillis) {
		// 生成JWT的时间,即签发时间 2021-10-30 10:02:00 -> 30 10:32:00
	
		long nowMillis = System.currentTimeMillis();
 
		
		//链式语法:
		// 下面就是在为payload添加各种标准声明和私有声明了
		// 这里其实就是new一个JwtBuilder,设置jwt的body
		JwtBuilder builder = Jwts.builder()
				// 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
				.setClaims(claims)
				// 设置jti(JWT ID):是JWT的唯一标识,根据业务需要,这个可以设置为一个不重复的值,主要用来作为一次性token,从而回避重放攻击。
				// 可以在未登陆前作为身份标识使用
				.setId(UUID.randomUUID().toString().replace("-", ""))
				// iss(Issuser)签发者,写死
				.setIssuer("zking")
				// iat: jwt的签发时间
				.setIssuedAt(new Date(nowMillis))
				// 代表这个JWT的主体,即它的所有人,这个是一个json格式的字符串,可放数据{"uid":"zs"}。此处没放
				// .setSubject("{}")
				// 设置签名使用的签名算法和签名使用的秘钥
				.signWith(SIGNATURE_ALGORITHM, JWT_KEY)
				// 设置JWT的过期时间
				.setExpiration(new Date(nowMillis + ttlMillis));
 
		return builder.compact();
	}
 
	/**
	 * 复制jwt,并重新设置签发时间(为当前时间)和失效时间
	 * 
	 * @param jwt
	 *            被复制的jwt令牌
	 * @param ttlMillis
	 *            jwt的有效时间(单位毫秒),当前时间+有效时间=过期时间
	 * @return
	 */
	public static String copyJwt(String jwt, Long ttlMillis) {
		//解密JWT,获取所有的声明(私有和标准)
		//old
		Claims claims = parseJwt(jwt);
 
		// 生成JWT的时间,即签发时间
		long nowMillis = System.currentTimeMillis();
 
		// 下面就是在为payload添加各种标准声明和私有声明了
		// 这里其实就是new一个JwtBuilder,设置jwt的body
		JwtBuilder builder = Jwts.builder()
				// 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
				.setClaims(claims)
				// 设置jti(JWT ID):是JWT的唯一标识,根据业务需要,这个可以设置为一个不重复的值,主要用来作为一次性token,从而回避重放攻击。
				// 可以在未登陆前作为身份标识使用
				//.setId(UUID.randomUUID().toString().replace("-", ""))
				// iss(Issuser)签发者,写死
				// .setIssuer("zking")
				// iat: jwt的签发时间
				.setIssuedAt(new Date(nowMillis))
				// 代表这个JWT的主体,即它的所有人,这个是一个json格式的字符串,可放数据{"uid":"zs"}。此处没放
				// .setSubject("{}")
				// 设置签名使用的签名算法和签名使用的秘钥
				.signWith(SIGNATURE_ALGORITHM, JWT_KEY)
				// 设置JWT的过期时间
				.setExpiration(new Date(nowMillis + ttlMillis));
		return builder.compact();
	}
}
 
 
 
 

3.4.Controller

When the back-end user logs in to request the address, write the code in the controller UserController

 @RequestMapping("/userLogin")
    @ResponseBody
    public JsonResponseBody<?> userLogin(UserVo userVo, HttpServletResponse response){
        if(userVo.getUsername().equals("admin")&&userVo.getPassword().equals("123")){
            //私有要求claim
            Map<String,Object> json=new HashMap<String,Object>();
            json.put("username", userVo.getUsername());
            //生成JWT,并设置到response响应头中
            String jwt=JwtUtils.createJwt(json, JwtUtils.JWT_WEB_TTL);
            response.setHeader(JwtUtils.JWT_HEADER_KEY, jwt);
            return new JsonResponseBody<>("用户登陆成功!",true,0,null);
        }else{
            return new JsonResponseBody<>("用户名或密码错误!",false,0,null);
        }
    }

3.5.Configuration

Configure the classes and filters written above in the background project ( Web.xml )

  <!--CrosFilter跨域过滤器-->
  <filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>com.junlinyi.ssm.util.CorsFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
 
  <!--JwtFilter-->
  <filter>
    <filter-name>jwtFilter</filter-name>
    <filter-class>com.junlinyi.ssm.jwt.JwtFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>jwtFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

3.6. Test class

When testing JWT, create a test class and write the following method

 Note: The following code needs to be added to the test class 

private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

Used to generate JWT 

Test method one: 

test1() 

	@Test
	public void test1() {// 生成JWT
		//JWT Token=Header.Payload.Signature
		//头部.载荷.签名
		//Payload=标准声明+私有声明+公有声明
		
		//定义私有声明
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put("username", "zss");
		claims.put("age", 18);
		
	    //TTL:Time To Live
		String jwt = JwtUtils.createJwt(claims, JwtUtils.JWT_WEB_TTL);
		System.out.println(jwt);
 
		//获取Payload(包含标准和私有声明)
		Claims parseJwt = JwtUtils.parseJwt(jwt);
		for (Map.Entry<String, Object> entry : parseJwt.entrySet()) {
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

 

Parse Jwt

Test method two: 

test2()  

Use the JWT string generated above to parse

	@Test
	public void test2() {// 解析oldJwt
		//io.jsonwebtoken.ExpiredJwtException:JWT过期异常
		//io.jsonwebtoken.SignatureException:签名异常
		String newJwt="eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ6a2luZyIsImV4cCI6MTY5NzE4Nzc0OSwiaWF0IjoxNjk3MTg1OTQ5LCJhZ2UiOjE4LCJqdGkiOiJlNGZlOWFjYWY0Njk0YTZmYjg4ZmVkNjE3NGEyZGUxZiIsInVzZXJuYW1lIjoienNzIn0.ThB8lHAw4mfPdwoTE6gnzWYN2hZbaNxvt4n2QYDOOEE";
		String oldJwt = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MzU1NjE3MjcsImlhdCI6MTYzNTU1OTkyNywiYWdlIjoxOCwianRpIjoiN2RlYmIzM2JiZTg3NDBmODgzNDI5Njk0ZWE4NzcyMTgiLCJ1c2VybmFtZSI6InpzcyJ9.dUR-9JUlyRdoYx-506SxXQ3gbHFCv0g5Zm8ZGzK1fzw";
		Claims parseJwt = JwtUtils.parseJwt(newJwt);
		for (Map.Entry<String, Object> entry : parseJwt.entrySet()) {
 
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

 

Copy jwt and delay for 30 minutes

Test method three: 

test3()  

Delay & copy the JWT string generated above

	@Test
	public void test3() {// 复制jwt,并延时30分钟
		String oldJwt = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ6a2luZyIsImV4cCI6MTY5NzE4Nzc0OSwiaWF0IjoxNjk3MTg1OTQ5LCJhZ2UiOjE4LCJqdGkiOiJlNGZlOWFjYWY0Njk0YTZmYjg4ZmVkNjE3NGEyZGUxZiIsInVzZXJuYW1lIjoienNzIn0.ThB8lHAw4mfPdwoTE6gnzWYN2hZbaNxvt4n2QYDOOEE";
		String newJwt = JwtUtils.copyJwt(oldJwt, JwtUtils.JWT_WEB_TTL);
		System.out.println(newJwt);
		Claims parseJwt = JwtUtils.parseJwt(newJwt);
		for (Map.Entry<String, Object> entry : parseJwt.entrySet()) {
 
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

 

Test the validity time of JWT

Test method four: 

test4()  

Test the validity time of the JWT string generated above

	@Test
	public void test4() {// 测试JWT的有效时间
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put("username", "zss");
		String jwt = JwtUtils.createJwt(claims, 3 * 1000L);
		System.out.println(jwt);
		Claims parseJwt = JwtUtils.parseJwt(jwt);
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

 

 Test parsing of expired JWT

Test method five: 

test5()  

Test parsing of expired JWT

	@Test
	public void test5() {// 三秒后再解析上面过期时间只有三秒的令牌,因为过期则会报错io.jsonwebtoken.ExpiredJwtException
		//String oldJwt = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MzU1NjMzODIsImlhdCI6MTYzNTU2MTU4MiwiYWdlIjoxOCwianRpIjoiN2RlYmIzM2JiZTg3NDBmODgzNDI5Njk0ZWE4NzcyMTgiLCJ1c2VybmFtZSI6InpzcyJ1.F4pZFCjWP6wlq8v_udfhOkNCpErF5QlL7DXJdzXTHqE";
		String oldJwt = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ6a2luZyIsImV4cCI6MTY5NzE4MDM2MywiaWF0IjoxNjk3MTc4NTYzLCJhZ2UiOjE4LCJqdGkiOiJmYmVhOTUyZDVlMTA0OTFiODA5MjkxNDcxNjNlMDIxYiIsInVzZXJuYW1lIjoienNzIn0.63jn2lHoFzIrWJ0yS_mTOSTlLebwcF2P2wlzutapIqs";
		Claims parseJwt = JwtUtils.parseJwt(oldJwt);
		// 过期后解析就报错了,下面代码根本不会执行
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

 

4. Application

Find the state.js file (src/store/state.js) in our spa project and write:

export default {
  eduName: '默认值~~',
  jwt: ''
}

Find the getters.js file (src/store/getters.js) in our spa project and write:

export default {
  getEduName: (state) => {
    return state.eduName;
  },
  getJwt: (state) => {
    return state.jwt;
  }
}

Find the mutations.js file (src/store/mutations.js) in our spa project and write:

export default {
  // type(事件类型): 其值为setEduName
  // payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
  setEduName: (state, payload) => {
    state.eduName = payload.eduName;
  },
  setJwt: (state, payload) => {
    state.jwt = payload.jwt;
  }
}

Find the main.js file in our spa project and write it: 

/* eslint-disable no-new */
window.mm = new Vue({
  el: '#app',
  router,
  store,
  data() {
    return {
      bus: new Vue()
    }
  },
  components: {
    App
  },
  template: '<App/>'
})

 Find the http.js file (src/api/http.js) in our spa project to write the request interceptor & response interceptor:

// 请求拦截器
axios.interceptors.request.use(function(config) {
  let jwt = window.mm.$store.getters.getJwt;
  if(jwt){
    config.headers['jwt'] = jwt;
  }
  return config;
}, function(error) {
  return Promise.reject(error);
});
 
// 响应拦截器
axios.interceptors.response.use(function(response) {
  //将响应头中的jwt字符串放入state.js中
  let jwt = response.headers['jwt'];
  if (jwt) {
    window.mm.$store.commit('setJwt', {
      jwt: jwt
    });
  }
  return response;
}, function(error) {
  return Promise.reject(error);
});

              That’s it for today, I hope I can help you! !

Guess you like

Origin blog.csdn.net/m0_74915426/article/details/133818281