Home > Net >  Run jQuery and Bootstrap in Spring MVC with Spring Security
Run jQuery and Bootstrap in Spring MVC with Spring Security

Time:10-11

I am new to spring boot MVC app development. I have a new application, that I set up through Maven, in which I am trying to import jquery and bootstrap. I imported both through Maven as Jar files. They reside in Java Resources->Libraries->Maven Dependencies.

I am using spring framework 5.3.22 and spring security 5.7.3

When I run my site, I can see the jquery and bootstrap files are added in the Network tab, but I get the following errors:

"Refused to execute script from [website url] because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled."

And

"Refused to apply style from [website url] because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled."

On my JSP page, I include the files like this:

<link href="webjars/bootstrap/5.2.0/css/bootstrap.min.css" rel="stylesheet" >
<script src="webjars/jquery/3.6.1/jquery.min.js" type="text/javascript"></script>
<script src="webjars/bootstrap/5.2.0/js/bootstrap.min.js" type="text/javascript"></script>

My Servlet config looks like this:

public class MySpringMvcDispatcherServeletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        //return DemoAppConfig.java class
        return new Class[] {DemoAppConfig.class};
    }
    @Override
    protected String[] getServletMappings() {       
        return new String[] {"/"};
    }    
}

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig  {    
@Bean
public InMemoryUserDetailsManager userDetailsManager() {
    System.out.println("======>> Add Details manager");
    //add in memory users/roles
}

@Bean
public CorsConfigurationSource corsConfigurationSource(){
    System.out.println("======>> Add CORS");
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    // Below config will allow only following origines from web browser
    corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:8080/"));
    // Whether user credentials are supported. By default, do not support
    // If you want to allow credentials then set it true
    corsConfiguration.setAllowCredentials(false);

    // below will not allow DELETE methods, if you want then add DELETE also
    corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "OPTION"));

    // Below will set allowed headers list, Other headers will not be supported
    corsConfiguration.setAllowedHeaders(Arrays.asList("accept", "authorization", "apikey", "tenantId"));

    UrlBasedCorsConfigurationSource  corsConfigurationSource = new UrlBasedCorsConfigurationSource();

    // This will register above configurations on all resources from the root
    // If you want different rules for different resources then create separate configuration
    // and register on separate resource path uri
    corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
    return corsConfigurationSource;
}

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    // Ignore resources for any check
    System.out.println("======>> Add  web Customizer");
    return (web) -> web.ignoring().antMatchers("/webjars/**","/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/icon/**");
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    System.out.println("======>> Add Security Chain");
    return http     
    .authorizeRequests(configurer ->
        configurer
            .antMatchers("/webjars/**","/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/icon/**").permitAll()
            .anyRequest().authenticated())
    
    .formLogin(configurer ->
        configurer
            .loginPage("/showMyLoginPage")
            .loginProcessingUrl("/authenticateTheUser")
            .permitAll())
    
    .build();  
}   

}

CodePudding user response:

I was able to do this by overriding addResrouceHandlers. In my DemoAppConfig file, which implements WebMvcConfigurer, I add this code:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.jason.springsecurity.demo")
public class DemoAppConfig implements WebMvcConfigurer{
    //define bean for ViewResolver
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        
        return viewResolver;    
    }   

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("================>Calling addResourceHandlers");
        
        //my libraries
        registry.addResourceHandler("/resources/**")
            .addResourceLocations("/resources/");
        
        //webjars
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
        }
    }   
}

I can then add the files to my Views like this:

<link href="webjars/bootstrap/5.2.0/css/bootstrap.min.css" rel="stylesheet" > 
<script src="webjars/jquery/3.6.1/jquery.min.js"></script>
<script src="webjars/bootstrap/5.2.0/js/bootstrap.min.js"></script>
  • Related