【问题标题】:Redirect to index.html when URL contained a potentially malicious String in spring boot当 URL 在 Spring Boot 中包含潜在的恶意字符串时重定向到 index.html
【发布时间】:2019-03-27 14:25:55
【问题描述】:

我正在开发一个应用程序,它以 spring boot 作为后端,angular 6 作为前端。我将所有前端文件构建到 Spring Boot 的静态文件夹中。在所有情况下,无论是(type=Internal Server Error, status=500) 错误还是(type=Not Found, status=404) 错误,我都希望我的应用不显示“Whitelabel 错误页面”,而是将用户重定向到 index.html 静态文件夹中的文件。我可以通过将以下代码添加到我的 WebMvcConfigurer 中来实现 404 错误代码:

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    //registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    registry.addResourceHandler("/**/*")
            .addResourceLocations("classpath:/static/")
            .resourceChain(true)
            .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath,
                                               Resource location) throws IOException {
                    Resource requestedResource = location.createRelative(resourcePath);
                    return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
                            : new ClassPathResource("/static/index.html");
                }
            });
}

但对于 500 错误代码无法获得相同的结果。例如,当我在地址栏中输入带有特殊字符的 url 时,我会收到以下错误:

**Whitelabel Error Page**

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Oct 23 13:56:11 IRST 2018
There was an unexpected error (type=Internal Server Error, status=500).
The request was rejected because the URL contained a potentially malicious String ";"   

但如果我输入了一些没有特殊字符的错误 url,我会被重定向到“index.html”文件。
我也尝试将这些行添加到我的 WebMvcConfigurer 中,但这也不起作用:

@Override
public void addViewControllers(final ViewControllerRegistry registry) {
    registry.addViewController("/notFound").setViewName("forward:/static/index.html");
    registry.addViewController("/login").setViewName("forward:/static/index.html");
    registry.addViewController("/error").setViewName("forward:/static/index.html");
}

@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
    return container -> {
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
        container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error"));
    };
}

【问题讨论】:

    标签: spring angular spring-boot


    【解决方案1】:

    不需要更多代码,您可以在静态目录中创建一个名为“public”的文件夹,并在创建名为“500.html”或“404.html”的文件之后在该文件夹中创建名为“error”的目录或错误目录中的 http_code.html 现在您可以重定向这些文件。

    【讨论】:

    • 感谢您的回复,但我希望它是一步过渡。你所说的将是一个两步重定向,一旦用户被重定向到“500.html”,然后到“index.html”。
    猜你喜欢
    • 2019-03-05
    • 2022-10-23
    • 2021-08-10
    • 2021-11-17
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2017-08-09
    相关资源
    最近更新 更多