this is my frist time when I decided to write application based on Spring Boot and Spring Security with full Java code configuration and I am experiencing weird problems that I cannot surpass. I am tryning to test API with Postman and my requests are only accepted when I use content-type as application/x-www-form-urlencoded. Below I am pasting my all current configuration.
@SpringBootApplication
public class OpenIdApplication {
public static void main(String[] args) {
SpringApplication.run(OpenIdApplication.class, args);
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserService userService;
@Autowired
public SecurityConfig(UserService userService) {
this.userService = userService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(11);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/register/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.cors()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
@RestController
public class UserController {
...
@PostMapping(value = "/register")
public ResponseEntity<Object> registerUser(
@RequestBody UserRegistrationDto newUser, BindingResult bindingResult) {
...
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserRegistrationDto {
private String username;
private String firstName;
private String lastName;
private String email;
private String password;
private String passwordRepeat;
}
If I want to login I can only do this with mentioned content-type. For application/json I am getting 403 response status. For /registration endpoint, if I remove @RequestBody from method parameter then it works fine with application/x-www-form-urlencoded request, but if I keep it then for this content-type I am getting 415, but if I try with application/json then I am seeing 403. I have also tried adding @PreAutorize("permitAll()") annotation above this endpoint, adding httpBasic() into Spring Security configuration - which resulted in changing response status from 403 to 401.
I have tried sending 2 different JSONs to that endpoint:
{
"username":"test",
"firstName":"Test",
"lastName":"Test",
"email":"[email protected]",
"password":"test",
"passwordRepeat":"test",
"_csrf":"8b7d4680-5be4-482a-9138-b4eb92a358c1"
}
{
"newUser": {
"username":"test",
"firstName":"Test",
"lastName":"Test",
"email":"[email protected]",
"password":"test",
"passwordRepeat":"test"
},
"_csrf":"8b7d4680-5be4-482a-9138-b4eb92a358c1"
}
Of course everytime I was making sure that _csrf matches the one returned from my API.
I am using Spring Boot 2.0.1.RELEASE and Spring Security 5.0.3.RELEASE.