A preface

After learning this article, readers will have a comprehensive understanding of the login authentication process of token class, and can dynamically build their own login authentication process; It’s a lightweight certification mechanism for small projects that meets development needs; More wonderful original content to pay attention to princess knowledge seekers, readers’ affirmation, is the biggest support for the author’s creation;

JWT realizes the login authentication process

  • A user makes a POST request using an account and face
  • The server receives the request and uses the private key to create a JWT, which generates the token
  • The server returns the JWT to the browser
  • The browser needs to put the JWT with the token in the request header
  • Each hand-to-client request, the server validates the TOKEN of the JWT
  • Verify that the resource successfully returns the response to the browser. Otherwise exception handling

Three related introduction to JWT

3.1 JWT composition

The token of JWT is composed of three pieces of information. Use these three pieces of information as text. Concatenated together to form a JWT string;

  • Header Header (which contains the metadata for the token and contains the type of the signature and/or encryption algorithm)
  • Payload load
  • Signature/visa
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODI4OTc4NDUsInVzZXJuYW1lIjoienN6eHoifQ.vyiExkFWCCmQA3PFYL0jJfIiYGWubngq B0WcgmtHOxgCopy the code

3.2 JWT advantages

  • Compact: Can passURL.POSTParameter or inHTTP headerSending, small amount of data, fast transmission speed
  • Self-contained: The payload contains all the information the user needs, avoiding multiple queries to the database
  • Because the.TokenBased onJSONEncrypted form is saved on the client side, soJWTIs cross-language support;
  • No need to save session information on the server, applicable to distributed and micro services;

Four JWT users log in and issue tokens

4.1 the pom. XML

The project artifacts are as follows

  • Springboot 2.1;
  • JWT 3.4.0;
  • Maven 3.5
  • jdk1.8
  • Postman interface test
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.auth0</groupId> <artifactId> Java -jwt</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional>
        </dependency>
    </dependencies>
Copy the code

4.2 JWT tools

There are three methods in the JWT tool class, which are to generate a digital signature to send JWT to the client when the user logs in for the first time. The second is the verification method, which is used for interceptor to intercept all urls within the rule. Each request must have JWT sent by the server, and only after verification, can the request be released. The last method to get a user name is used to query the key, passed in as a parameter when validating JWT;

/* * * @author LSC * <p> JWT </p> * @param * @return */ public class JwtUtil {// Token expiration time 30 minutes public static final long EXPIRE_TIME = 30 * 60 * 1000; /* * * @author LSC * <p> verify token is correct </p> * @param token * @param username * @param secret * @return Boolean */ public static boolean verify(String token, String username, String secret) {try {// Set encryption Algorithm Algorithm = algorithm.hmac256 (secret); JWTVerifier verifier = JWT.require(algorithm) .withClaim("username", username)
					.build();
			// 效验TOKEN
			DecodedJWT jwt = verifier.verify(token);
			return true;
		} catch (Exception exception) {
			return false; }} /* * * @author LSC * <p> </p> secret] * @Return java.lang.String */ public static String sign(String username, String secret) { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); // With username informationreturn JWT.create()
				.withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } /* * * @author LSC * <p> get user name </p> * @param [request] * @return java.lang.String */ public static String getUserNameByToken(HttpServletRequest request) { String token = request.getHeader("token");
		DecodedJWT jwt = JWT.decode(token);
		return jwt.getClaim("username") .asString(); }}Copy the code

4.3 User Entities

The entity contains the user name, the password, everything simple;


/**
 * @Author lsc
 * <p> </p>
 */
@Data
public class SysUser {

    private String username;

    private String password;

}

Copy the code

4.4 the Controller

Presentation layer Code User Login authentication. After the authentication is successful, the token is issued to the client.

/**
 * @Author lsc
 * <p> </p>
 */
@RestController
public class SysUserController {

    @PostMapping(value = "/login") public Map<String, Object> login(@RequestBody SysUser sysUser){ Map<String, Object> map = new HashMap<>(); String username = sysUser.getUsername(); String password = sysUser.getPassword(); String Token = jwtutil. sign(username,password); // Omit account password authentication.if(token ! = null){ map.put("code"."200");
            map.put("message"."Certification successful");
            map.put("token", token);
            return map;
        }
        map.put("code"."403");
        map.put("message"."Authentication failed");
        returnmap; }}Copy the code

4.5 test

The test url http://localhost:8080/login

The postman POST request test parameters are as follows

{
	"username": "zszxz"."password": "zszxz"
}
Copy the code

Return the following

{
    "code": "200"."message": "Certification successful"."token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODI4OTc4NDUsInVzZXJuYW1lIjoienN6eHoifQ.vyiExkFWCCmQA3PFYL0jJfIiYGWubng qB0WcgmtHOxg"
}
Copy the code

Five JWT login interception certification

Based on the JWT login authentication, the token is issued to the client. This section is to put the token into the request header and send the request to the server. The server authenticates the token by intercepting the request with an interceptor; The authentication succeeds. Otherwise, the resource request fails.

5.1 Custom Interceptors

Custom JwtInterceptor, which implements the HandlerInterceptor interface, verifies the token validity before each request arrives;

/** * @author LSC * <p> </p> */ @component public class JwtInterceptor implements HandlerInterceptor { @Autowired SysUserService sysUserService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handler) throws Exception {// Fetch token from HTTP request header String Token = Request.getheader ("token"); // If not mapped to the method directly throughif(! (handler instanceof HandlerMethod)){return true;
        }
        if(token ! = null){ String username = JwtUtil.getUserNameByToken(request); // The user name should be checked by the database to obtain the password. Steps in the service directly access password Boolean result = JwtUtil. Verify (token, username, sysUserService. GetPassword ());if(result){
                System.out.println("Pass the interceptor.");
                return true; }}return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
Copy the code

5.2 the service

/** * @author LSC * <p> */ @service public class SysUserService {public StringgetPassword() {return "zszxz"; }}Copy the code

5.3 Interceptor Configuration

Interceptor configuration mainly defines interception request rules, the interceptor into WebMvcConfigurer; Cors cross-domain processing;

/* * * @author LSC * <p> * @param * @return */ @configuration public class InterceptorConfig implements WebMvcConfigurer {/* * * @author LSC * <p> Sets the interceptor path </p> * @param [registry] * @return void */ @override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authenticationInterceptor()) .addPathPatterns("/ * *")
                .excludePathPatterns("/login"); } / * * * @ Author LSC * < p > the interceptor into the context of < / p > * @ Param [] * @ Return com ZSZXZ. JWT. The interceptor. JwtInterceptor * / @ Bean public JwtInterceptorauthenticationInterceptor() {
        returnnew JwtInterceptor(); } /* * * @author LSC * <p> Cross-domain support </p> * @param [registry] * @return void */ @override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/ * *")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET"."POST"."DELETE"."PUT"."PATCH"."OPTIONS"."HEAD") .maxAge(3600 * 24); }}Copy the code

5.4 the Controller

The presentation layer interface is used to intercept affinity tests

/**
 * @Author lsc
 * <p> </p>
 */
@RestController
public class TestController {

    @GetMapping(value = "/api/test")
    public String get() {return "zszxz"; }}Copy the code

5.5 test

The test url http://localhost:8080/api/test

Send a GET request to the server with a request header. The key is token and the value is the token string returned by the user when he logs in for the first time.

The test returns the following content

zszxz
Copy the code

Vi Official website Link

JWT. IO/introductio…

Source code attention princess or author column can be obtained;