1

End points are developed using sping boot with security i.e.(spring security). login api is working fine with proper http basic authentication. enter image description here

From postman i can able the fetch the data, with other endpoints after login. enter image description here

But, when i have integrated in react, call the api with the axios is not working. Also getting 401 status code. enter image description here

Entire code

SecurityConfig.class
@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
          CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
            corsConfiguration.setAllowedOrigins(List.of("*"));
            corsConfiguration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PUT","OPTIONS","PATCH", "DELETE"));
            corsConfiguration.setAllowCredentials(true);
            corsConfiguration.setExposedHeaders(List.of("Authorization"));
            
        http.cors(Customizer.withDefaults());
        http.csrf().disable();
        http.authorizeHttpRequests()
                .antMatchers("/user/login", "/swagger-resources/configuration/ui", "/swagger-resources",
                        "/swagger-resources/configuration/security", "/swagger-ui.html", "/webjars/**")
                .permitAll().anyRequest().authenticated().and().httpBasic().and().logout().logoutUrl("/logout");
        return http.build();
    }
@PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginDto) {
        Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(loginDto.getUser_id(), loginDto.getPassword()));

        if (authentication.isAuthenticated()) {
            User user = userRepository.findEmailByStatus(loginDto.getUser_id(), "ACTIVE").get();
            ApiResponse response = new ApiResponse(200, "Successfully Logged in", user);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
        if (!authentication.isAuthenticated()) {
            return new ResponseEntity<>("Bad Credentials", HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>("something went wrong", HttpStatus.INTERNAL_SERVER_ERROR);
    }

Bank

@GetMapping
    public ResponseEntity<?> getBankList() {
        try {
            List<Bank> list = bankRepository.findAll();
            System.out.println(list);
            if (list == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new CustomResponseEntity("Bank Not Found on This Id - ", "Bad_Request"));
            }
            if (list != null) {
                System.out.println(list);
                return ResponseEntity.status(HttpStatus.OK).body(list);
            }
        } catch (Exception e) {
            log.info("Found an issue at " + new Date() +" | "+ e.getCause().getMessage());
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(new CustomResponseEntity("Bank Not Found on This Id - ", "Bad_Request"));

    }

React code is here

Login

const login = () => {
    axios.post("http://localhost:9091/v2/user/login", {
      user_id:"abc@abc.com",
      password:"123456"
   }).then(
     (response=> {
       setfirst(response.data)
       console.log(response.data);
     })
   ).catch(error=>{
     console.log("error",error);
     setfirst(error.response)
   })  
  }

Bank

const bank = () => {
    axios.get("http://localhost:9091/v2/bank").then(
     (response=> {
       console.log(response.data);
     })
   ).catch(error=>{
     console.log("error",error);
   })  
  }

From react, i can able to login, unable to fetch bank data. getting 401 status enter image description here

Also getting error in react enter image description here

how to fix this

I tried implementing cors code in spring security configurations. still getting the same issue.

Is there any alternate way to fix this issue or is something wrong with code.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Raj Kumar
  • 13
  • 4
  • Please enable TRACE logs in spring security and show us them. – Toerktumlare May 31 '23 at 07:28
  • `http.cors(Customizer.withDefaults());` is looking for an exposed bean, therefor you have to expose `corsConfiguration`. – dur May 31 '23 at 08:14
  • BTW: You cannot use `corsConfiguration.setAllowedOrigins(List.of("*"));` and `corsConfiguration.setAllowCredentials(true);` at the same time. You have to change `*` to an URL. – dur May 31 '23 at 08:18
  • the bank endpoint is protected by Spring Security and you don't send any information for authentication. How do you expect this to work? – grekier May 31 '23 at 19:14

0 Answers0