Java SpringBoot uses interceptor as the implementation method of privilege control

  • 2021-11-24 01:45:36
  • OfStack

How to achieve

First of all, the interceptor belongs to web, so we need to introduce springboot web module, and the specific version is in parent


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Then we create a new interceptor directory under the config directory to put interceptors

We create two new interceptors, one for login interception and one for administrator interception. Needless to say, login interception is to judge whether all requests except login requests have been logged in. If there is no login request, we will truncate the request, but it will return to a failed state Administrator intercepts, intercepts the resources that administrators can access, such as user management/authority management, etc. It can only be carried out after landing intercepts and releases. It's like a level is one level and one level. After login verification, enter administrator verification to judge whether the login user has administrator authority, if so, release, otherwise intercept and return to failure state The core of the interceptor is to implement the interface org. springframework. web. servlet. HandlerInterceptor. Verification Logic 1 is written in the preHandle method My verification logic is relatively simple. Login verification is to take out user information from session and judge whether it exists. User information is put into session when logging in successfully. You can also use JWT for verification Administrator validation is also from the session to take out the administrator information, judge whether it is an administrator, administrator information is successful login will be administrator information into session, you can also use JWT validation

Landing interceptor


package com.example.interceptor_demo.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
 *  Interceptor, login check 
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private HttpSession session;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Object user = session.getAttribute("sessionUser");
        if (sessionUser!=null){
            return true;
        }else {
            Map<String,Object> notLogin = new HashMap<>();
            notLogin.put("msg","not login");
            notLogin.put("code",403);
            notLogin.put("data",null);
            try(PrintWriter printWriter = response.getWriter()){
                printWriter.print(objectMapper.writeValueAsString(notLogin));
            }catch (Exception e){
                e.printStackTrace();
            }
            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 {
    }

}

Administrator interceptor


package com.example.interceptor_demo.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
 *  Interceptor, administrator authentication 
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private HttpSession session;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Boolean isAdmin = (Boolean)session.getAttribute("sessionAdmin");
        if (isAdmin!=null && isAdmin){
            return true;
        }else {
            Map<String,Object> notLogin = new HashMap<>();
            notLogin.put("msg","no power");
            notLogin.put("code",403);
            notLogin.put("data",null);
            try(PrintWriter printWriter = response.getWriter()){
                printWriter.print(objectMapper.writeValueAsString(notLogin));
            }catch (Exception e){
                e.printStackTrace();
            }
            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 {
    }

}

Finally, we create a new WebMvcConfig class in the config directory to register the interceptor

The core of the interceptor registration class is the implementation of the org. springframework. web. servlet. config. annotation. WebMvcConfigurer interface Implement the addInterceptors method, and the parameter registry object can be used to register the interceptor The registry. addInterceptor () method is used to add an interceptor The. addPathPatterns () method is to add the intercept resource path to the interceptor The. excludePathPatterns () method is to add the resource path for the interceptor to pass Where * stands for any name under the path, ** stands for any name under any path

package com.example.interceptor_demo.config;

import com.example.interceptor_demo.config.interceptor.AdminInterceptor;
import com.example.interceptor_demo.config.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Autowired
    private AdminInterceptor adminInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        this.loginInterceptor(registry);// Login interception         
        this.adminInterceptor(registry);// Administrator interception 
    }

    private void loginInterceptor(InterceptorRegistry registry){
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(// Release the login interface 
                        "/login/**"
                );
    }

    private void adminInterceptor(InterceptorRegistry registry){
        registry.addInterceptor(htmlPageInterceptor)
                .addPathPatterns("/admin/**");// Intercept administrator interface 
    }
}

Related articles: