I made an API using spring boot. I also implemented Spring Security. I have a login controller:
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/login")
public class LoginController {
private final UserService userService;
public LoginController(UserService userService){
this.userService = userService;
}
@PostMapping("")
public ResponseEntity login(@RequestBody AuthDTO auth){
return ResponseEntity.status(HttpStatus.OK).body(userService.findByNameAndPassword(auth));
}
}
In my SecurityConfig file, I implemented securityFilterChain() as shown below:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.cors(cors->cors.disable())
.authorizeRequests()
.requestMatchers("/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
Although I disable CORS, I still have problems when I make requests from my login page, created in React using JavaScrpit. I use this object, axios, to make the requests:
axiosInstance.post("/login", credentials)
.then(
res => {
const val = res.data;
console.log("Success");
console.log(val);
if (val.id !== 0 ) {
alert("Logged in!");
<Route exact path="/login" element={<User/>}/>
}
else
{
alert("Eroare!");
}
}
)
.catch(error => {
console.log(error)
})
When I request to login, I get the error mentioned in the title. I tried to put in the header of axios the bearer key. In postman, using the bearer key, I can communicate without a problem with the API. But from my React login page, I cannot make any request, even when I try to send the bearer key. I tried changing @CrossOrigin annotation, specifying Access-Control-Allow-Origin, but with no effect.This is my axios class:
import axios from "axios"
const axiosInstance = axios.create({
baseURL: "http://localhost:8080/",
headers: {
post: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
}
}
});
export default axiosInstance;