Issue
I would like to secure my urls in the following way:
posting to "/user/": only those that are not logged in
all other requests should be logged in
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
//auth method omitted for brevity
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/user/").anonymous()
.antMatchers("/**").hasAnyRole("USER")
.and()
.httpBasic();
}
@Bean //replace with bcrypt later
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
This is my controller class:
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/")
public UserShallowDTO getUser(Authentication auth) {
return new UserShallowDTO(); //just an empty object with null properties for testing purposes
}
// @PreAuthorize("!isAuthenticated()")
//@PostMapping("/")
public ResponseEntity<SuccessResponse> AddUser(@RequestBody UserDTO userDTO) {
// stuff here
}
@PostMapping("/")
public String PostTestMethod() {
return "hello";
}
}
The problem is it keeps returning 401 error on postman when I POST. However, when I change the config to GET rather than POST, the get method of the controller works as intended.
How can I solve this issue?
Solution
This issue is related to CSRF
. By default CSRF
is enabled in Spring
.
you can disable it in your configuration method.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
Reference: Spring Security CSRF
Answered By - Sajjad
Answer Checked By - Marilyn (JavaFixing Volunteer)