Facing an issue while trying to submit a form to the /policy-holder page using fetch in JavaScript. The endpoint is redirecting to the login page, even though only admins are supposed to login. What could be causing this problem and how can it be resolved? I have already attempted to add permitted all to the security config for the endpoint, but with no success. Additionally, basic auth does not work simultaneously with cookie auth. How can this be fixed?
@PostMapping("/policy-holder")
public ResponseEntity<PolicyHolder> createPolicyAndBeneficiaries(@RequestBody @Validated PolicyHolderRequestDto policyHolderDto) {
return policyHolderService.createPolicyAndBeneficiaries(policyHolderDto);
}
Service.
@Transactional
public ResponseEntity<PolicyHolder> createPolicyAndBeneficiaries(PolicyHolderRequestDto policyHolderDto) {
paymentGateway.verifyAccount(policyHolderDto.accountNumber(), "050");
PolicyHolder ph = PolicyHolder.builder()
.accountNumber(policyHolderDto.accountNumber())
.phoneNumber(policyHolderDto.phoneNumber())
.lastName(policyHolderDto.lastName())
.firstName(policyHolderDto.firstName())
.email(policyHolderDto.email())
.build();
PolicyHolder savedPolicyHolder = policyHolderRepository.save(ph);
Security
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) ->
authorize.requestMatchers("/register/**","/css/**","/js/**", "/images/**").permitAll()
.requestMatchers("/").permitAll()
.requestMatchers("/index").permitAll()
.requestMatchers("/policy-holder").permitAll()
.requestMatchers("/users","/send").hasRole("ADMIN")
.anyRequest().authenticated()
).formLogin(
form -> form
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/users")
.permitAll()
).logout(
logout -> logout
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.permitAll()
);
return http.build();
}
JavaScript
fetch('/policy-holder', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(extractedData),
})
.then(response => response.json())
.then(data => {
console.log('POST request response:', data);
// Handle the response data as needed
})
.catch(error => {
console.error('Error making POST request:', error);
// Handle the error
});