Search code examples
javaspringspring-bootspring-mvcspring-security

how to allow static folder and css files in spring security as antMtchers is dperecated


package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.builders.WebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.config.annotation.web.configuration.*;
import com.example.service.CustomUserDetailsService;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    CustomUserDetailsService customUserDetailsServcie;

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeHttpRequests()
            .requestMatchers("/registration", "/password-request", "/reset-password", "../static/css",
                "../static/images")
            .permitAll().requestMatchers("home").permitAll().and().formLogin().loginPage("/login")
            .loginProcessingUrl("/login").defaultSuccessUrl("/home", true).permitAll().and().logout()
            .invalidateHttpSession(true).clearAuthentication(true)
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout")
            .permitAll();
        return http.build();
    }

    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(customUserDetailsServcie).passwordEncoder(passwordEncoder());

    }

}

I have watch videos and read post but everywhere I see only solutions using antMatchers . Most of the post in stackoverflow are old and now as antMatchers doesnt work in latest spring there isnt any proper solultion.


Solution

  • You need to add

    http.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
    

    to configure Spring Security to allow unauthenticated access to the resources under src/main/resources/static. Also, remove

    "../static/css", "../static/images"

    from your configuration.