0

I'm new to spring security, and I try to implement an athorisation in my project. Everything work's fine, but the images and css files are not loaded. I'm using the (annotations) way to configure it.

Here is my project structure:

project structure

The configuration of resource mapping in 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/" />

My 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 Security configuration:

@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");
    }
}

I'm trying to load the css file like this:

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

and the images like this:

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

As a result, the images are not displayed, and the css files are getting error:

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. 

What am I doing wrong? Are there some configuration problems? I searched a lot, but I didn't find some solutions that can help me. I will be very thankful for your help.

2
  • please check this, if it helps. stackoverflow.com/questions/48248832/… Commented Jun 2, 2018 at 12:41
  • Thank's Shrikant Havale. I've just minified the css file, but I'm still geting this error. Commented Jun 2, 2018 at 13:05

2 Answers 2

2

In Spring boot add image folder in /src/main/webapp/WEB-INF/images

In Config file

@Configuration
public class AppConfig implements WebMvcConfigurer {

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

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {     

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

    }
}

In Security

@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       
}
Sign up to request clarification or add additional context in comments.

Comments

0

I suggest you to add the beans:

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

in your dispatcher spring-web-servlet.xml and then simply call

<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"/> 

1 Comment

Thank you very much for you answer. I tried it, but it doesn't seems to work. The image is still not displayed, and css is not loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.