#CORS Issue trying when trying to get from frontend

9 messages · Page 1 of 1 (latest)

robust orbit
#

Here's my security config


import com.reeftrader.Hades.user.User;
import com.reeftrader.Hades.user.UserService;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
(deleted some imports to fit this post limit)
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfig {

    private final JwtAuthFilter jwtAuthFilter;

    private final AuthenticationProvider authenticationProvider;

    private final static List<UserDetails> APPLICATION_USERS = Arrays.asList(
            new org.springframework.security.core.userdetails.User(
                    "email.com",
                    "pas",
                    Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN"))
            )
    );

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));//TODO: Use ENV variable here for URL
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT", "PATCH"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(c -> c.configurationSource(corsConfigurationSource()))
                .csrf()
                .disable()
                .authorizeHttpRequests()
                // requestMatchers makes a list of "white listed" request that do not request AUTHENTICATION
                .requestMatchers("/user/**", "/event", "/listing/event/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}

and my controller


import com.reeftrader.Hades.listing.Listing;
import com.reeftrader.Hades.listing.ListingRequest;
import com.reeftrader.Hades.listing.ListingResponse;
import com.reeftrader.Hades.listing.ListingService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/reservation")
@RequiredArgsConstructor
public class ReservationController {

    private final ReservationService reservationService;

    @GetMapping("identity/{identityId}")
    public ResponseEntity<List<Reservation>> getReservationsForIdentity (@PathVariable Integer identityId) {
        return ResponseEntity.ok(reservationService.getReservationsForIdentity(identityId));
    }
}
pastel quarryBOT
#

This post has been reserved for your question.

Hey @robust orbit! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

robust orbit
#

I've added the URL to allowed origins and annotated the controller... not sure why it is still blocking it

restive musk
#

Probably the story as usual, you're trying to use CORS through HTTP without SSL, which is a pain in the ass. All the tutorials on the internet assume that you use HTTPS, because that's how it should be done.

#

Remove that CORS code and use a proxy.

robust orbit
restive musk
#

Lol, no, proxy is the easiest way to solve it. In React it's literally a single line of config.

robust orbit
#

Figured this out it's actually really simple to enable CORS with http

All I was missing was setting the allowed headers in the corsConfigurationSource() method like so:
configuration.setAllowedHeaders(Arrays.asList("*"));
For a full production working version you'll want to swap out the allowOrigins array with an env variable URL