-3

I have a spring-boot app (that implements Spring security) related to react app in the front. When I do rest calls (GET, POST, ..), it works fine without any issues. However, When I try to call Stripe checkout from my react app, I get this error :

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://r.stripe.com/0. (Reason: CORS request did not succeed). Status code: (null)

Here's my code

SecurityConfig.java

protected void configure(HttpSecurity http) throws Exception {
    String[] staticResources  =  {
            "/api/clients/authentication/**",
            "/api/repas/**"
    };
    http = http.cors().and().csrf().disable();

    http = http
            .exceptionHandling()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and();

    http
            .authorizeRequests()
            .antMatchers(staticResources).permitAll()
            .anyRequest().authenticated();

    http.addFilterAfter(jwtFilter, ExceptionTranslationFilter.class);
}

CorsConfiguration.java

Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH","OPTIONS")
                        .allowedOrigins("https://m.stripe.com/6","https://r.stripe.com/0","http://localhost:3000")
                        .exposedHeaders("*")
                        .allowedHeaders("*");
            }
        };
    }

I tried to put "*" in the allowed origins but it didn't work either. I tried to create a bean in the security config file to enable cors and deleted the cors configuration file (like below) but then all the calls, even those to my rest APIs have failed.

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source =
            new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

Update: This code in the front is what causes the issue ProfilPayment.java

export default function ProfilPayment() {
const [clientSecret, setClientSecret] = useState("");
const headers = {
    'Content-Type': 'application/json',
    "Access-Control-Allow-Origin": "*",
    'Access-Control-Allow-Methods': "*",
    'Authorization': `Bearer ${localStorage.getItem("token")}`
}
const URL_API_HTTP = "http://localhost:8080/api/clients/authentication/create-payment-intent";

async function handlePayment() {
    console.log("if it works, this line should be shown");
    try {
        const response = await axios.post("http://localhost:8080/api/clients/authentication/create-payment-intent",{headers});
        const data = response.data;
    console.log(data);
    console.log(typeof data);
    setClientSecret(data);
    }catch(error) {
    alert(error.message);}
}

return (
        <Card sx={{width: 250 ,height: 670, display: "inline" ,float: "left"}} style={{ border: "none", boxShadow: "none" }}>
            <CardContent>
                <Typography sx={{fontSize: 20, color: "#ef6800"}} color="text.secondary" gutterBottom >
                    Mode de paiement
                </Typography>
                <br/>
                <Typography sx={{ fontSize: 12}} variant="body2" >
                    <br />
                    <br />
                    <ProfilButton value="Ajouter une carte" onClick={handlePayment}/>
                </Typography>
                <Typography>
                    {clientSecret && (
                    <Elements options={clientSecret} stripe={stripePromise}>
                       { <CheckoutForm /> }
                    </Elements>
                    )}
                </Typography>
            </CardContent>
        </Card>
);

}

Hamadi95
  • 1
  • 3
  • Isn't all of that junk you're configuring related to Spring's capacity as a web *server*? But you're making requests to that as a web *client*. You haven't shown the place where you create the request either. – Michael Nov 21 '22 at 10:56
  • the checkout of Stripe payment is calling the page "r.stripe.com/0" in the background, that's why I didn't provide the code for the front, but for the calls related to localhost, it works fine. – Hamadi95 Nov 21 '22 at 11:55
  • 1
    Regardless of whether it's in the background, you are calling something which eventually produces the request, and you haven't shown that. All the code in the your question is completely unrelated to the problem. – Michael Nov 21 '22 at 12:02

3 Answers3

1

The r.stripe.com domain is only used for tracking metrics and it should not have any impact on the ability to make payments. So you can ignore these types of error.

soma
  • 1,332
  • 1
  • 2
  • 8
0

Since you can directly make get and post calls without error, the issue may be at the front end level.

I had the same problem when running an angularjs front end with http-server. I had to use the command "http-server -p 3000 --cors" to make cors works when launching the front end.

Maybe you can refer to this post for solution. How to allow CORS in react.js?

zhangde
  • 74
  • 4
-1

I figured out what was the problem: the error of CORS wasn't the main issue.

Here is the updated code that works in the frontend(which uses React and Stripe).

ProfilPayment.java:

const appearance = {
        theme: 'stripe',
};
const options = {
        clientSecret,
        appearance,
      };
{ clientSecret && (
        <Elements options={options} stripe={stripePromise}>
            { <CheckoutForm /> }
                </Elements>
            )
}

flyingfishcattle
  • 1,817
  • 3
  • 14
  • 25
Hamadi95
  • 1
  • 3