Spring Boot 未返回正确的 MIME 类型

问题描述 投票:0回答:5

我正在尝试使用 Spring boot、Spring Security 和 Thymeleaf 制作一个 Spring MVC 应用程序。

问题是 - 当我请求包含 html 和 css 的页面时,我没有获得 css 文件的正确 MIME 类型,因此 Chrome 无法以状态“canceled”和消息“”加载它拒绝应用来自“http://localhost:8080/login”的样式,因为其 MIME 类型(“text/html”)不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。

我正确链接了 css 文件: ” “

css文件包含在:

资源 -> 静态 -> css -> style.css

我已允许安全配置文件中资源文件夹中的所有资源:

    package org.isp.configuration;

import org.isp.services.api.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider
                = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(this.userService);
        authProvider.setPasswordEncoder(getBCryptPasswordEncoder());
        return authProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] permitted = new String[]{
                "/", "/home","/register","/about","/png/**",
                "/css/**","/icons/**","/img/**","/js/**","/layer/**"
        };

        http
                .authorizeRequests()
                .antMatchers(permitted).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").permitAll()
                .defaultSuccessUrl("/dashboard")
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
                .logout().logoutSuccessUrl("/login?logout").permitAll()
                .and()
                .exceptionHandling().accessDeniedPage("/unauthorized")
                .and()
                .csrf().disable();
    }

    @Bean
    public BCryptPasswordEncoder getBCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

这是我的html页面:

<!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" 
         xmlns:th="http://www.thymeleaf.org" >
    <head>
        <title>Index</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        **<link rel="stylesheet" href="../static/css/style.css" type="text/css">**
    </head>
    <body>
        <div th:include="~{fragments/navbar :: navbar}"></div>

        <div class="container">
            <h3>Home</h3>
            <p>This is the home page of the project!</p>
        </div>

        <div th:include="~{fragments/footer :: footer}" class="footer"></div>
    </body>
    </html>

有什么想法可以修复不正确的 MIME 类型吗?是否缺少任何配置?

html css spring spring-boot
5个回答
13
投票

我一直在努力解决同样的问题,最后我意识到这是一个转移注意力的问题——真正的问题是

404
,MIME类型错误来自于Spring对它的处理。如 Spring Boot 文档 中所述,其内置错误处理会自动重定向到
/error
并将错误详细信息输出为 JSON。当我检查日志时,我在网络服务器访问日志中看到了
404
,并在应用程序日志中看到了以下内容:

DEBUG DispatcherServlet:869 - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /error
DEBUG RequestMappingHandlerMapping:317 - Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
DEBUG HttpEntityMethodProcessor:234 - Written [{timestamp=Fri Apr 06 14:06:54 PDT 2018, status=404, error=Not Found, message=No message available, path=/css/style.css}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@5ef96137]

所以,你真正的问题是 Spring 没有找到你的静态资源。您需要确保

resources
文件夹位于类路径中,或者使用
spring.resources.static-locations
属性显式设置位置。


13
投票

就我而言,我必须允许静态文件请求才能使其正常工作。

@Configuration 
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 @Overide
 protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/js/**", "/css/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll();
  }
}

1
投票

就我而言,我使用了额外的过滤器。因此,所有类型的请求都将通过该过滤器。甚至 css 和 js 文件也曾经经历过这个过程。

此时,对于某些比例为 1/7 或 1/10 的请求,我遇到 mime 类型问题,对于 css 文件,服务器返回 application/javascript 或 application/json 等类型。

然后我使用了 @WebFilter 并只允许 api 请求通过该过滤器。

@WebFilter(urlPatterns = "/api/*")

现在该附加过滤器中不允许使用 css 和 js 文件。然后我没有发现 mime 类型的问题。

在我看来,当我们有太多过滤器时,后端无法处理频繁的资源请求(js、css、img ...),因此它返回错误的 MIME 类型。

希望,这可以帮助面临此类问题的人


0
投票

今天(2021 年 11 月 24 日),一个客户遇到了这样的情况:Spring Security 将大多数请求的 URL 重定向到“/login”等效功能端点。未加载任何资产,并且您在 Google Chrome 控制台日志中收到有关 mimetype 的相同消息。

通过输入具有错误 mimetype 的资产并查看“/login”端点的加载来完成诊断。

通过在 Spring Boot 应用程序的 SecurityConfig.class 中添加一些 Spring Security 映射规则解决了这个问题,因此 web 应用程序现在运行良好。


0
投票

同样,我也面临着这种类型的错误,现在我解决了该错误,只改变了这个 如果您在 springboot 项目中使用 thymeleaf,请使用 html 代码。

然后只更改此代码

                      or 

© www.soinside.com 2019 - 2024. All rights reserved.