0

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;
ChJ16
  • 51
  • 1
  • 9
  • If you want to allow CORS, it makes no sense to disable it with `.cors(cors->cors.disable())`. you have to enable it. – dur May 04 '23 at 08:31

1 Answers1

1

As you are doing Cross Domain request. CORS will not allow until you configure it. By disabling it won't solve the problem.

You can configure globally using following configuration.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000") // your reactjs URL
                .allowedMethods("GET", "POST", "PATCH", "PUT", "DELETE")
                .allowedHeaders("Content-Type") // Adjust headers you need to allow
                .allowCredentials(true); // Add only if you want to access cookie
    }

}

Also check in Browser developer console. The request response headers. Does it contains Access-Control-* headers? use http.cors() first in your security configuration.

Dhaval Gajjar
  • 2,508
  • 1
  • 2
  • 13