SpringBoot Security 4xx 5xx 自定义错误页面

在使用spring security时,如果没有查询到访问权限会抛AccessDeniedException
由于spring security采用filter方式进行链式校验,而自定义的权限过滤器在ExceptionTranslationFilter异常解析过滤器后面,因此当抛出上述异常时会被前一个ExceptionTranslationFilter捕获,并根据异常类型进行解析,状态码403,如果在WebSecurityConfigurerAdapter中定义了http.exceptionHandling().accessDeniedPage("/");
则会直接通过请求转发到响应的错误页面,否则会通过tomcat错误页面进行转发

StandardHostValve

 //如果是web.xml中定义了errorPage页面,则会被加载进去,直接通过状态码获取
ErrorPage errorPage = context.findErrorPage(statusCode);
        if (errorPage == null) {
            // Look for a default error page
           //springBoot在启动时如果没有定义错误页面会自动生成一个0的错误页面 访问地址默认为/error
            errorPage = context.findErrorPage(0);
        }
        if (errorPage != null && response.isErrorReportRequired()) {
            response.setAppCommitted(false);
            request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE,
                              Integer.valueOf(statusCode));

            String message = response.getMessage();
            if (message == null) {
                message = "";
            }
            request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);
            request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR,
                    errorPage.getLocation());
            request.setAttribute(Globals.DISPATCHER_TYPE_ATTR,
                    DispatcherType.ERROR);


            Wrapper wrapper = request.getWrapper();
            if (wrapper != null) {
                request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME,
                                  wrapper.getName());
            }
            request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
                                 request.getRequestURI());
            //请求转发
            if (custom(request, response, errorPage)) {
                response.setErrorReported();
                try {
                    response.finishResponse();
                } catch (ClientAbortException e) {
                    // Ignore
                } catch (IOException e) {
                    container.getLogger().warn("Exception Processing " + errorPage, e);
                }
            }
        }

tomcat最终会转发到ErrorPage中定义的location指定的地址并将错误信息等传递过去(转发默认不会经过filter),
最终会通过DispatcherServlet执行Controller逻辑

因此我们只需要实现一个/error的Controller即可,而在springBoot系统默认实现

BasicErrorController

@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {

        @RequestMapping(produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request,
            HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
                request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
                //SpringBoot 4xx 5xx通用错误页面,就是因为没有定义错误页面它会取默认的error页面
                //而error页面定义就是在ErrorMvcAutoConfiguration中定义的
        return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
    }
    @Override
    public String getErrorPath() {
        return this.errorProperties.getPath();
    }
    @RequestMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }
}

有两种视图模式 一个是页面 一个是json,如果需要自定义格式或者页面的话 需要重新上述两个方法

所有错误状态码的请求在没有定义错误页面时都会通过BasicErrorController

默认情况下 只需要将404.html等放到下面目录下的error文件夹下面即可
[/META-INF/resources/, /resources/, /static/, /public/]

server.error.path 用来指定errorPage的父级路径
如果项目中采用spring security,在自定义错误页面时 getErrorPath()一定要this.errorProperties.getPath();否则会被拦截;

题外话,

  • 如何添加springBoot ErrorPage页面呢?

TomcatEmbeddedServletContainerFactory

public EmbeddedServletContainer getEmbeddedServletContainer(
            ServletContextInitializer... initializers) {
        Tomcat tomcat = new Tomcat();
        File baseDir = (this.baseDirectory != null ? this.baseDirectory
                : createTempDir("tomcat"));
        tomcat.setBaseDir(baseDir.getAbsolutePath());
        Connector connector = new Connector(this.protocol);
        tomcat.getService().addConnector(connector);
        customizeConnector(connector);
        tomcat.setConnector(connector);
        tomcat.getHost().setAutoDeploy(false);
        configureEngine(tomcat.getEngine());
        for (Connector additionalConnector : this.additionalTomcatConnectors) {
            tomcat.getService().addConnector(additionalConnector);
        }
        prepareContext(tomcat.getHost(), initializers);
        return getTomcatEmbeddedServletContainer(tomcat);
    }

springboot在创建tomcat容器时,会调用上述方法在prepareContext方法中的configureContext方法中会
添加ErrorPage错误页面

protected void configureContext(Context context,
            ServletContextInitializer[] initializers) {
        TomcatStarter starter = new TomcatStarter(initializers);
        if (context instanceof TomcatEmbeddedContext) {
            // Should be true
            ((TomcatEmbeddedContext) context).setStarter(starter);
        }
        context.addServletContainerInitializer(starter, NO_CLASSES);
        for (LifecycleListener lifecycleListener : this.contextLifecycleListeners) {
            context.addLifecycleListener(lifecycleListener);
        }
        for (Valve valve : this.contextValves) {
            context.getPipeline().addValve(valve);
        }
        for (ErrorPage errorPage : getErrorPages()) {
            new TomcatErrorPage(errorPage).addToContext(context);
        }
        for (MimeMappings.Mapping mapping : getMimeMappings()) {
            context.addMimeMapping(mapping.getExtension(), mapping.getMimeType());
        }
        configureSession(context);
        for (TomcatContextCustomizer customizer : this.tomcatContextCustomizers) {
            customizer.customize(context);
        }
    }

因此只需要通过实现EmbeddedServletContainerCustomizer类中的customize方法addErrorPages添加错误页面即可,在默认情况下ServerCustomization实现了该接口,同时添加了一个状态码为0的ErrorPage,同时它是直接采用server.error.path作为全路径

注意,需要使用springBoot自身定义的ErrorPage接口

另外一种定义错误页面方法

private static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {

        private final ServerProperties properties;

        protected ErrorPageCustomizer(ServerProperties properties) {
            this.properties = properties;
        }

        @Override
        public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
            ErrorPage errorPage = new ErrorPage(this.properties.getServletPrefix()
                    + this.properties.getError().getPath());
            errorPageRegistry.addErrorPages(errorPage);
        }

        @Override
        public int getOrder() {
            return 0;
        }

    }

上述代码依赖版本 SpringBoot 1.5.6

  • 另外听说springboot 2.0上述方法定义错误页面无效(暂未接触)

猜你喜欢

转载自blog.csdn.net/weixin_34405925/article/details/86806951
今日推荐