Home  >  Article  >  Spring security prevents access to styles

Spring security prevents access to styles

WBOY
WBOYforward
2024-02-22 13:19:061178browse

php editor Banana brings you the latest Java Q&A content: How does security in the Spring framework prevent access to styles? This is an important issue when it comes to web application security. When developing web applications using the Spring framework, how to effectively protect style files from unauthorized access is an issue that needs attention. This article will answer this question in detail for you and help you better improve the security of web applications.

Question content

I ran into a problem where at some point some styles in my spring project stopped working. I used bootstrap styles and styles written by myself in css files. For some reason after launching the program, only part of it is displayed. When viewing "Network" in Google Developer Tools, I see that the style files are being redirected to http://localhost:8080/login for some reason, although I can access the style files. (https://i.stack.imgur.com/ggort.png)

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((requests) -> requests
                        .requestMatchers("/", "/reg", "/registration/**", "/static/**", "/static/images/**", "/static/styles/**").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin((form) -> form
                        .loginPage("/login")
                        .failureUrl("/login_error")
                        .defaultSuccessUrl("/pc")
                        .permitAll()
                )
                .logout((logout) -> logout.permitAll().logoutSuccessUrl("/"));

        return http.build();
    }

After discovering this, I decided to comment out the spring security dependency in pom.xml and comment out all classes that use it. After that the styles started working and everything continued to work when spring security was not annotated. However, when I restarted my computer and started the project, I ran into the same problem again. What could this be related to and how to fix it? I really need your help!

Solution

You need to tell Spring Security to ignore resources under src/main/resources/static. You can do this by adding http.authorizeRequests((requests) -> requests..requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()) to the security configuration and removing all "/static/ to achieve this. .. A reference from an existing configuration.

The above is the detailed content of Spring security prevents access to styles. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete