SpringBoot custom interceptor to intercept login authentication to achieve

Login authentication interceptor to intercept one of the more common scenarios. We want to do for the user is not logged in to intercept, block access to other pages simultaneously jump to login page, then you need to use the interceptors. Of course, you can also use the more mature framework, such as Shiro is relatively good, but how do we achieve this function themselves, following by configuring custom interceptor, the way to learn about the interceptor.

1. Log Controller implementation

We are here only a simple simulation scenarios.

@Controller
public class AuthController {
    @GetMapping("/login")
    public String login(){

        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("token", "authorized");  //对于登录的用户在session中添加登录标记

        return "login";
    }

}

2, configure blocking rules

Due to the high SpringBoot version we use, HandlerInterceptorwe have achieved all methods, so we only method to achieve this before the visit.

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        System.out.println("preHandle");
        HttpSession session = request.getSession();
        if ("authorized"!=session.getAttribute("token")) {  //校验登录标记
            request.getRequestDispatcher("/login").forward(request, response);  //对于未登录的用户跳转到登录页面
            return false;
        }
        return true;
    }
}

3, configuration WebMvcConfigurer interceptor

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new AuthInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/login")  //过滤掉登录页面
            .excludePathPatterns("/static/**");  //过滤掉静态资源
    }
}

By the above simple configuration login authentication interceptor a custom realized.

Published 141 original articles · won praise 131 · views 210 000 +

Guess you like

Origin blog.csdn.net/qq_41621362/article/details/105337661