ali-bouali / spring-boot-3-jwt-security

Sample project on how to implement JWT security based using Spring boot 3 and Spring security 6
https://aliboucoding.com/p/securing-your-spring-boot-3-0-applications-with-json-web-tokens-jwt
Apache License 2.0
1.86k stars 870 forks source link

CORS error on sending authenticated request from a different route #19

Closed juliantjg closed 1 year ago

juliantjg commented 1 year ago

I'm trying to call an authenticated only API from a react server on localhost:3000, and got a CORS error: The CORS request requires preflight, preflighting could not be performed.. Anyone encountered this problem yet? I tried disabling the cors from the securityChainFilter but to no avail. Thanks

marcosfaneli commented 1 year ago

You need to add cors configuration: 1 - In method seucrityFilterChain add this:

http.csrf().disable() .cors().configurationSource(corsConfigurationSource()) .and()

    ...

2 - Add this method to create your config:

private CorsConfigurationSource corsConfigurationSource() { final var configuration = new CorsConfiguration();

configuration.setAllowedOriginPatterns(List.of("*"));
configuration.setAllowedMethods(List.of("GET", "POST", "PATCH",

"PUT", "DELETE")); configuration.setAllowCredentials(true); configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));

final var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);

return source;

}

Marcos Faneli | Software Developer 11 96411 2246 br.linkedin.com/in/marcosfaneli/pt

On Sat, Mar 18, 2023 at 10:40 PM Julian Tjiong @.***> wrote:

I'm trying to call an authenticated only API from a react server on localhost:3000, and got a CORS error: The CORS request requires preflight, preflighting could not be performed. . Anyone encountered this problem yet? I tried disabling the cors from the securityChainFilter but to no avail. Thanks

— Reply to this email directly, view it on GitHub https://github.com/ali-bouali/spring-boot-3-jwt-security/issues/19, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACOJB2IMJN4PKVP2F4C7PV3W4ZP2RANCNFSM6AAAAAAV7ZT5KY . You are receiving this because you are subscribed to this thread.Message ID: @.***>

ali-bouali commented 1 year ago

as @marcosfaneli mentioned, you need to add a cors configuration if you want to access the backend from a browser (frontend application for example)