【问题标题】:spring security doesn't load the resources (images, css)spring security 不加载资源(图像,css)
【发布时间】:2018-06-02 12:35:21
【问题描述】:

我是 Spring Security 的新手,我尝试在我的项目中实施 athorisation。一切正常,但未加载图像和 css 文件。我是用(注解)的方式来配置的。

这是我的项目结构:

dispatcher spring-web-servlet中资源映射的配置:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />

我的 web.xml

<servlet>
    <servlet-name>spring-web</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>
    <servlet-name>spring-web</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/errors/error404.jsp</location>
</error-page>

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
            </filter-class>
</filter>

<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

Spring 安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    PersistentTokenRepository tokenRepository;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()

            .antMatchers("/").permitAll()
            .antMatchers("/resources/**").permitAll() .anyRequest().permitAll()
            .antMatchers("/*.css","/*.jpg").permitAll().anyRequest().permitAll()
            .antMatchers("/css/**", "/js/**","/img/**", "/webjars/**", "**/favicon.ico", "/index").permitAll().anyRequest().permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
            .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
            .antMatchers("/users/**").access("hasRole('ROLE_USER')")
            .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
            .usernameParameter("username").passwordParameter("password")
            .loginProcessingUrl("/j_spring_security_check")
            .defaultSuccessUrl("/users/users_page")
                .and()
            .logout().logoutUrl("/j_spring_security_logout").logoutSuccessUrl("/login?logout")
                .and()
            .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository).tokenValiditySeconds(86400)
                .and()
            .csrf().disable();

    }

    @Bean
    public PasswordEncoder passwordEncoder(){
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            return encoder;
    }

    @Bean
    public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
        PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
                "remember-me", userDetailsService, tokenRepository);
        return tokenBasedservice;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/*.css");
        web.ignoring().antMatchers("/*.jpg");
    }
}

我正在尝试像这样加载 css 文件:

 <link rel="stylesheet" type="text/css" 
       href="<c:url value="${pageContext.request.contextPath}/resources/static/css/test_style.css"/>"

还有这样的图片:

<img src="<c:url value='/resources/static/img/head.jpg' />" type="image/jpg"  alt="BigLogo" height="650"  width="1000"/> 

结果图片不显示,css文件报错:

Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. 

我做错了什么? 是否存在一些配置问题? 我搜索了很多,但我没有找到一些可以帮助我的解决方案。 我将非常感谢您的帮助。

【问题讨论】:

标签: java spring-mvc spring-security configuration


【解决方案1】:

在 Spring Boot 中添加图像文件夹 /src/main/webapp/WEB-INF/images

在配置文件中

@Configuration
public class AppConfig implements WebMvcConfigurer {

......
......

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {     

 registry.addResourceHandler("/images/*").addResourceLocations("/WEB-INF/images/");

    }
}

在安全方面

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()                
                .antMatchers("/").permitAll()           
                .antMatchers("/images/*").permitAll()

//To display the image on first landing page to all users       
}

【讨论】:

    【解决方案2】:

    我建议你添加 bean:

    <mvc:resources mapping="/css/**" location="/resources/static/css/" />
    <mvc:resources mapping="/img/**" location="/resources/static/img/" />
    

    在您的调度程序 spring-web-servlet.xml 中,然后简单地调用

    <link rel="stylesheet" type="text/css" href="./css/test_style.css"/>"
    <img src="./img/head.jpg" type="image/jpg" alt="BigLogo" height="650"  width="1000"/> 
    

    【讨论】:

    • 非常感谢您的回答。我试过了,但它似乎不起作用。图片还是没有显示,css也没有加载。
    猜你喜欢
    • 2014-10-11
    • 2014-12-04
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2012-11-15
    相关资源
    最近更新 更多