I'm actually trying to access the method at that endpoint but I keep getting the classic CORS error "Access to XMLHttpRequest at 'http://localhost:8080/rpc-measurements' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
@JsonRpcService("rpc-measurements")
public interface JsonRpcAPI {
public List<Measurements> getMeasurementsByDays(String username, int days);
public Float getAvgEnergyConsumption();
public String getUsername(String username);
}
The implementation:
@Service
@AutoJsonRpcServiceImpl
public class JsonRpcAPIimpl implements JsonRpcAPI {
@Autowired
private MeasurementsRepository measurementsRepository;
@Autowired
private DeviceRepository deviceRepository;
@Autowired
private PersonRepository personRepository;
@Override
public List<Measurements> getMeasurementsByDays(String username, int days) {
Person person = personRepository.findByName(username);
List<Device> devices = deviceRepository.findByPersonId(person.getId());
List<Measurements> measurements = new ArrayList<>();
devices.forEach(x -> {
measurements.addAll(measurementsRepository.getEnergyConsumptionForDays(UuidAdapter.getBytesFromUUID(x.getId()), days));
});
return measurements;
}
@Override
public Float getAvgEnergyConsumption() {
return 0.0f;
}
@Override
public String getUsername(String username) {
return username;
}
}
The security configuration file:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource(name = "userService")
private CustomUserService userService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
.anyRequest().permitAll()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
/*http.csrf().disable().authorizeRequests()
.anyRequest().permitAll();*/
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Autowired
private UnauthorizedEntryPoint unauthorizedEntryPoint;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationFilter();
}
}
And finally the react js function that calls the API:
function handleValueSelect(event) {
axios.post(REST_API_URL + '/rpc-measurements', {
id: "1",
jsonrpc: "2.0",
method:"getAvgEnergyConsumption",
params:[]
},{
headers: {
Authorization: "Bearer " + localStorage.getItem('userToken')
}
}).then(res => {
setDataP(res.data.map((data) => ({
time: ((data.time.split('T')[1])
.split('+')[0])
.split('.')[0],
value: data.value
})));
});
};
I have been wasting half a day trying to find some solutions, most of the problems related to the CORS policy error that I found on the internet were solved by either adding the @CrossOrigin annotation to a controller or by adding http.cors() in the security configuration file, the thing is that I am not trying to access an endpoint from a controller I am trying to access an endpoint from a json rpc service in order to use a method from there and I have no idea if I have to set up cross origin for that particular path in a different way compared to a controller (where you just use the annotation, and yes I already tried adding it to the service).
The weirdest thing is that I tried accessing the URL in postman with exactly the same body as in the axios request and it worked, but when I tried in the web client the CORS error kept popping up. I even tried creating a Rest Controller and using JsonRpcRestClient to invoke the method but it didn't work, it freezes my spring app, I don't even get an error or an exception in the console, it just stops responding.
So I wanted to ask if there's someone who's been in a similar situation or has some ideas on how to deal with the CORS policy error taking into account that I am trying to access an end point from a Service and not a controller.