Spring Security Does Not Allow CSS or Js Resources to Be Loaded

Spring security does not allow CSS or JS resources to be loaded

You probably want to make sure to have your directory containing those items set as permitAll.

Here's an excerpt from my spring security context file. Under the resources directory, I have js, css, and images folders which are given permissions by this line.

<security:intercept-url pattern="/resources/**" access="permitAll" />

Can't load my css when using spring security and thymeleaf

override this method configure(WebSecurity web) too and modifie code like below

 @Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/vendor/**","/fonts/**");
}
}

Spring Security not serving static content

Supposing that your static files are under src/main/resources:

Sample Image

There are two main pieces to configure:

Implement the WebMvcConfigurer interface to discover your static resources:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/assets/**")) {
registry.addResourceHandler("/assets/**")
.addResourceLocations("/assets/");
}
}
}

Setup your security configuration to allow static resources (such as CSS, JavaScripts and images) to be publicly accessible:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

// Your settings

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

// Your AuthN handlers and filter chain...

http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/img/**").permitAll()
.antMatchers("/js/**").permitAll()
.anyRequest().authenticated();

// Logout handler...
}
}

Supposing that you have a CSS file as follows:

src/main/resources/assets/css/layout.css

The web server will make it accessible at:

http://<root_url>:<port>/css/layout.css

Spring can't load css before login, but after login everything is ok

I found a solution to my own question.
I insert this code in the class I mentioned in the question and I created folder images in resource -> static. Previously I have all files images files and .css mixed directly in static without folders.

 String[] staticResources = {
"/css/**",
"/images/**",
"/fonts/**",
"/scripts/**",};

This is how whole class looks now

package com.example.dnevnikjartest.configuration;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
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.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

private AuthenticationSuccessHandler authenticationSuccessHandler;

@Autowired
public SecurityConfiguration(AuthenticationSuccessHandler authenticationSuccessHandler) {
this.authenticationSuccessHandler = authenticationSuccessHandler;
}

@Autowired
private DataSource dataSource;

@Value("${spring.queries.users-query}")
private String korisniciQuery;

@Value("${spring.queries.roles-query}")
private String ulogeQuery;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().usersByUsernameQuery(korisniciQuery).authoritiesByUsernameQuery(ulogeQuery)
.passwordEncoder(bCryptPasswordEncoder).dataSource(dataSource);

}

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

String[] staticResources = {
"/css/**",
"/images/**",
"/fonts/**",
"/scripts/**",};

http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/resource/**").permitAll()
.antMatchers("/roditelj/**").hasAuthority("roditelj")
.antMatchers("/admin/**").hasAuthority("admin")
.antMatchers("/ucitelj/**").hasAuthority("ucitelj")
.antMatchers(staticResources).permitAll()
.anyRequest()
.authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error=true")
.successHandler(authenticationSuccessHandler)
.usernameParameter("username")
.passwordParameter("password").and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
}

Spring isn't loading CSS and gives a 404 when the page is loaded

For a non-Spring Boot project your css folder should be not in src/main/resources but in src/main/webapp.

Doesn't connect css files in my project based Spring boot

You shouldn't use resources in href, and by convention you put static files like css, js and such into resources/static/and then use th:href="@{styles/main_styles.css}

also just to make sure it isn't spring security blocking it, I always added following in my security config:

 @Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/vendor/**","/fonts/**").anyRequest();
}

ps:
Btw I couldnt help but notice - dnt use package names in plural - convention is singular so not controllers but controller. You have to think that package name will be read as a whole line com.sportify.Sportify.controllers.HomeController which will be then used in import statements

For the same reason only class name starts with capital letter and you shouldn't repeat package names - so correct would be com.yoursuranme.sportify.controller package structure. But this is just to provide info for future reference.



Related Topics



Leave a reply



Submit