SpringBoot integration with Jwt

Jwt profile

JSON Web Token is the most popular cross-domain authentication solution. It is suitable for identity authentication when data interaction between the front end and back end is implemented through Restful apis

Jwt composition (.separated) eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTkxNjQ4NjEsInVzZXJuYW1lIjoiYWRtaW4ifQ.fo5a-H_C7XG3fSnNdCEMzM2QmrF5c7yy pzoSxGzgJOo

Header: Contains the signature algorithm and token type

Payload: The information you attach to the token, such as the user’s name, so that you can retrieve the information directly from it after you verify the token instead of looking it up in the database

Signature: Indicates the Signature of the first two parts to prevent data tampering

The interaction process

This article will show you how to integrate Jwt in a few simple steps, without further ado. (Note: To use Lombok, download the relevant plug-ins and dependencies.)

  • Add Jwt dependencies to the project’s POM files
<! ---jwt--> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4. 0</version>
        </dependency>
Copy the code
  • Configure the account password in the project’s YML file
Login:
  username: admin
  password: admin
Copy the code
  • Create the user entity class
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/ * * *@author admin
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    @notnull (message = "ID cannot be empty ")
    private Integer id;

    @notblank (message=" name cannot be blank ")
    @length (min = 2, Max = 4, message = "name name must be between {min} - {Max} ")
    private String username;

    @notblank (message=" password cannot be blank ")
    @length (min = 5, Max = 10, message = "password must be between {min} - {Max} ")
    private String password;

}
Copy the code
  • Create the Jwt (Build/validate) utility class
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang.StringUtils;

import java.util.Calendar;

/ * * *@author admin
 */
public class JWTUtils {

    /** * Obtain token *@param u user
     * @return token
     */
    public static String getToken(User u) {
        Calendar instance = Calendar.getInstance();
        // The default token expiration time is 7 days
        instance.add(Calendar.DATE, 7);

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("userId", u.getId())
                .withClaim("username", u.getUsername());

        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(u.getPassword()));
    }

    /** * Returns token */
    public static DecodedJWT verify(String token) throws MyException {
        if(StringUtils.isEmpty(token)){
            throw new MyException("Token cannot be empty");
        }

        // Get the real password of the logged-in user if the database finds 123456
        String password = "admin";
        JWTVerifier build = JWT.require(Algorithm.HMAC256(password)).build();
        return build.verify(token);
    }

   /* public static void main(String[] args) { DecodedJWT verify = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTcxMDg1MDAsInVzZXJuYW1lIjoiYWRtaW4ifQ.geBEtpluViRUg66_P7ZisN3I _d4e32Wms8mFoBYM5f0"); System.out.println(verify.getClaim("password").asString()); } * /
}
Copy the code
  • Create a Jwt interceptor (intercepts all request validation tokens)
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.chentawen.springbootall.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/ * * *@author admin
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            throw new MyException("Token cannot be empty");
        }
        try {
            JWTUtils.verify(token);
        } catch (SignatureVerificationException e) {
            log.error("Invalid signature! Error - >", e);
            return false;
        } catch (TokenExpiredException e) {
            log.error("The token expired! Error - >", e);
            return false;
        } catch (AlgorithmMismatchException e) {
            log.error("Token algorithm inconsistent! Error - >", e);
            return false;
        } catch (Exception e) {
            log.error("The token is invalid! Error - >", e);
            return false;
        }
        return true; }}Copy the code
  • Inject interceptors into SpirngMVC
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/ * * *@author admin
 */
@Configuration
public class IntercaptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JWTInterceptor())
                // Intercepted path
                .addPathPatterns("/ * *")
                // Exclude the login interface
                .excludePathPatterns("/user/login");
    }
Copy the code
  • Create Controller to test
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/ * * *@author admin
 */
@RestController
@RequestMapping("user")
public class UserLoginController {

    @Value("${Login.username}")
    private String realUsername;

    @Value("${Login.password}")
    private String realPassword;

    @GetMapping("login")
    public String login(String username, String password) {
        if (username.equals(realUsername) && password.equals(realPassword)) {
            User u = new User();
            u.setPassword(password);
            u.setUsername(username);
            return JWTUtils.getToken(u);
        }
        return "Login failed! Wrong account or password!";
    }

    @GetMapping("test")
    public String test(a)  {
        return "Access test-API"; }}Copy the code
  • Use Postman for testing

Login interface – Returns Jwt

Test interface – Returns no permission

Test interface – Request header token, access successful

What doubt can comment area to ask! Thumb up! Please forward! For collection!