I am working on a small project where I used spring security. Before I used spring security, I was sending a post request using fetch. As soon as I implemented spring security, the requests were blocked. I am new to Spring Security so I am lost as to what I should do.
This is the fetch request:
<script>
document.getElementById('ratingSubmit').addEventListener('click', () => {
let stars = document.querySelectorAll('input[name="star-rating"]');
let selectedValue = null;
for (let i = 0; i < stars.length; i++) {
if (stars[i].checked) {
selectedValue = stars[i].value;
break;
}
}
if (selectedValue !== null) {
const url = window.location.search;
const urlParams = new URLSearchParams(url);
if (urlParams.has('id')) {
const id = urlParams.get('id');
console.log(selectedValue);
console.log(id);
fetch("/movie/rate", {
method: 'POST',
headers: {
'Content-type' : 'application/json'
},
body: JSON.stringify({movie_id : id, rating : selectedValue})
}).then((resp) => {
return resp.text();
}).then((resp) => {
let message = 'Failed to submit';
if (resp === 'Success')
message = `Successfully submitted a rating of ${selectedValue} stars`;
alert(message)
})
}
} else {
alert("No stars were selected");
}
});
</script>
The controller responsible for the rating is this one
package javaproj.movieRental.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import javaproj.movieRental.DTO.RatingRequest;
import javaproj.movieRental.entities.Rating;
import javaproj.movieRental.entities.User;
import javaproj.movieRental.repositories.MovieRepository;
import javaproj.movieRental.repositories.RatingRepository;
import javaproj.movieRental.repositories.UserRepository;
import javaproj.movieRental.security.CustomUserDetails;
import javaproj.movieRental.services.RatingServicesImp;
@Controller
@RequestMapping("/movie/rate")
public class RatingController {
@Autowired
private UserRepository userRepository;
@Autowired
private RatingRepository ratingRepository;
@Autowired
private MovieRepository movieRepository;
@PostMapping(consumes = "application/json", produces = "application/json")
public ResponseEntity<?> saveRating(@RequestBody RatingRequest rr, Authentication authentication) {
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
User user = userDetails.getUser();
Long user_id = user.getId();
Long movie_id = rr.getMovie_id();
int rating = rr.getRating();
System.out.println("User id: " + user_id + "nMovie id: " + movie_id + "nRating: " + rating );
Rating userRating = ratingRepository.getByUserIdAndMovieId(user_id, movie_id);
if (userRating != null) {
userRating.setRating(rating);
ratingRepository.save(userRating);
return ResponseEntity.ok("Success");
}
RatingServicesImp rsi = new RatingServicesImp(ratingRepository, userRepository, movieRepository);
userRating = rsi.createRating(user_id, movie_id, rating);
ratingRepository.save(userRating);
return ResponseEntity.ok("Success");
}
}
And in my SecurityConfiguration.java file, I am trying to enable POST requests to the /movie/rate path in this way
@Bean
public SecurityFilterChain securityFilterChain2(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize ->
authorize
.requestMatchers(HttpMethod.POST, "/movie/rate")
.hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated() // All other requests require authentication
)
.formLogin(formLogin ->
formLogin
.loginPage("/login") // Custom login page URL
.successHandler(customAuthenticationSuccessHandler) // Use custom success handler
.permitAll()
)
.logout(logout ->
logout
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll()
)
.exceptionHandling(exception ->
exception
.accessDeniedPage("/error/403") // Custom 403 error page
);
return http.build();
}
I keep getting the same error when I try to submit the post request
“POST http://localhost:8080/movie/rate 404 (Not Found)”