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.
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:
- Understanding CSRF
- What is the reason to disable csrf in spring boot web application?
- Reason to disable CSRF in spring boot
Or investigate more on how to make your POST requests work with CSRF: