Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring Security receiving 401 on Post Request

Hi I am learning Spring but when i felt starting convenient working with it, of course I came to a problem again… But this time I couldn’t find any explanation even after hours of searching.

Problem
When doing a Post request I get a 401. If I do the get request everything works fine.
I created multiple Post request with and without Requestbody but allways the same problem. Also if I disable the authentication by using : .requestMatchers("/api").permitAll() I still get a 401 for the POST Request.

First I thougth about cors but first of all I am using postman and second of all Post without json shouldn’t be a problem. usually.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Reproduce Problem

I created the following minimal project to reproduce the problem:

Spring Security Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        .anyRequest().authenticated()
                )
                .httpBasic(Customizer.withDefaults());

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails userDetails = User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(userDetails);
    }

}

Spring Controller

@RestController
@RequestMapping("/api")
public class MainController {

    @GetMapping
    public String helloGet() {
        return "Hello from Get";
    }

    @PostMapping
    public String helloPost() {
        return "Hello from Post";
    }


}

>Solution :

Try adding

http.csrf(csrf -> csrf.disable()); // or .csrf(AbstractHttpConfigurer::disable)

into your securityFilterChain method.

If that works, it confirms that the "problem" was CSRF. Then I suggest read more on CSRF to check that it’s safe disable it for your use case:

Or investigate more on how to make your POST requests work with CSRF:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading