In my SpringBoot App (ver. 3.0.2) I'm trying to implement endpoint with basic authentication using Spring Security
The issue is the endpoint always throws 403 Forbidden no matter if I'm running UnitTest or call endpoint via Postman.
What is wrong in this implementation ? Thanks in advance!
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User
.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER_ROLE")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(8);
}
}
@RestController
@RequestMapping("/person")
public class PdfReceiptController {
@Autowired
private PdfDocumentService pdfDocumentService;
@Autowired
private PdfDocumentRepositoryImpl pdfDocumentRepository;
@Autowired
public JdbcTemplate jdbcTemplate;
@PostMapping(value = "/{id}")
public ResponseEntity<?> createReceipt(@PathVariable String id) {
//...
}
}
JUnit Test:
@Slf4j
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@Transactional
@AutoConfigureMockMvc
class PdfReceiptControllerTest extends BaseTest {
@Autowired
private PdfDocumentRepositoryImpl pdfDocumentRepository;
@Autowired
protected MockMvc mockMvc;
@Test
void createReceipt_wrongPassword_unauthorized() throws Exception {
UserDetails user = User.builder()
.username("user")
.password("password")
.roles("USER_ROLE")
.build();
Authentication userAuthCredentials = new TestingAuthenticationToken(user, null, "USER_ROLE");
mockMvc.perform(post(String.format("/person/%s", "100"))
.with(authentication(userAuthCredentials)))
.andExpect(status().isUnauthorized());
}
}