How to allow Spring Security 6 to permit general ressources (static, images, etc...)

124 Views Asked by At

I'm on Spring Security 6, and having a trouble when rending pages: as I'm using Thymeleaf, the static repertory isn't allowed.

This is my filter

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/auth/**")
                        .permitAll()
                    .anyRequest()
                        .authenticated())
         
        return httpSecurity.build();
    }

When try to add

@Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/static");
    }

it seem as depreciated.

But When I edit the filter like this

.authorizeHttpRequests(auth -> auth
                    .requestMatchers("/**")
                        .permitAll()

Everything is correct.

May someone know by what it has been replaced ..??

thanks !!!

1

There are 1 best solutions below

0
On
You have to give static resources access, Hope below steps can help 

- Keep all your css/js/images under static => dist folder 

- update securityFilterChain method with below code 

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/auth/**", "/dist/**")
                        .permitAll()
                        .anyRequest()
                        .authenticated());

        return httpSecurity.build();
    } 



- try load css/js/images like below Thymeleaf code

 <link rel="stylesheet"   th:href="@{/dist/css/style.css}" />

 <script type="text/javascript" th:src="@{/dist/js/jquery-3.6.0.min.js}"></script>

 <img th:src="@{/dist/images/your_image.png}" alt="" />