JWT learning notes -- springboot integrated JWT usage

In the last note, I completed the interface test of verifying the token, which can use the method of checking the token every time to protect the interface in the project.

Question:

Another problem arises. Suppose there are 10 interfaces that should be protected. In addition to their own parameters, these 10 interfaces also need to transmit token data as parameters every time, and each method needs to verify the token. This causes a lot of code redundancy and is not flexible enough.

Optimization / solution:

For Java Web projects, you can put jwt validation in interceptors.

For spring cloud distributed projects, jwt authentication can be placed in the gateway.

——The current project is a Java Web project, so it is optimized by interceptor——

1, Interceptor

New package: interceptors

Class: JWTInterceptor

public class JWTInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        //Get token in request header
        String token = request.getHeader("token");
        try{
            JWTUtils.verify(token);
            return true;//Release request
        } catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","Invalid signature!");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg","token be overdue!");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg","Inconsistent algorithm!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg","token Invalid!");
        }
        map.put("state",false);//Set status
        //Convert map to json jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
  1. Inherit HandlerInterceptor interface
  2. Override the preHandle preprocessing method
  3. The official does not recommend that jwt be passed in the form of request parameters. It is recommended that jwt be hidden in the request header.
  4. If the verification is successful, you don't need to return the request success information from map, just return true and continue to release; Except for the successful verification, the request is regarded as a failure, return false, and respond the map to the front end in the form of Json to inform the front end of the reason for the failure of the request.

2, Interceptor configuration

Package: config

Class: InterceptorConfig

@Configuration
public class InterceptorConfig implements WebMvcConfigurer{

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JWTInterceptor())
                .addPathPatterns("/admin/test")         //Other interface token verification
                .excludePathPatterns("/admin/login");   //All administrator users are released
    }
}

Intercept path: all interface paths need to exclude the method path of user login to verify user name and password. This interface is used to authenticate users and generate token s, and cannot be intercepted. Because it is a demo, it is written here specifically to intercept the test method and not the login method.

3, Deletion of method code in controller class

    @PostMapping("/test")
    public Map<String,Object> test() {
        Map<String, Object> map = new HashMap<>();
        //Handle your own business logic
        map.put("state",true);
        map.put("msg","Request succeeded!");
        return map;
    }

Test 1: no token

The information obtained by the front end is set in the preHandle method of the interceptor.

Test 2: the valid token is put into the request header, and the request is successful

 

Tags: Java http jwt

Posted by thedon on Mon, 09 May 2022 09:39:05 +0300