Spring Security CORS: How to configure CORS in Spring Boot & Spring Security
Вставка
- Опубліковано 21 сер 2024
- In this tutorial, you will learn how to configure Cross-Origin Resource Sharing (CORS) with Spring Boot and Spring Security. CORS is an HTTP header-based mechanism that lets you specify in a flexible way what kind of cross-domain requests should be authorized. You will learn how to configure CORS in a Spring Boot application at a controller, method, and global level. You will also learn what to configure when you bring Spring Security into your application.
🔗Resources & Links mentioned in this video:
Github Repo: github.com/dan...
Cross-Origin Resource Sharing (CORS) MDN developer.mozi...
👋🏻Connect with me:
Website: www.danvega.dev
Twitter: / therealdanvega
Github: github.com/dan...
LinkedIn: / danvega
Newsletter: www.danvega/de...
SUBSCRIBE TO MY CHANNEL: bit.ly/2re4GH0 ❤️
Finally, someone who is actually well prepared and not high while explaining this subject
Hi Dan! I just wanted you to know that I just discovered your channel while looking for a solution to this CORS error. Not only you explained ir on a way that a simple person can understand it, but also, you were very clear on how to fix this problem, so I want to say thanks for all this information, and let you know that your work is very apreciated! And for sure, you have a new subscriber ;). Cheers from Argentina!
I am glad to have a teacher like you 🎉
Took my doubts away. I love Spring Boot now.
Dan, attending this was so helpful , Many thanks
Glad it was helpful!
Dan, you saved my life with this.
Thanks a lot .
After a long Time of difficulties
Your video helped me to overcome my problem with cors and security
You sir have earned a new subscriber 💯 Magnificent tutorial on CORS.
Thank you so much!
I just started thinking about how to deal with cors like yesterday! what are the odds!! thanks boss perfect video!
Happy to help out Max!
Thanks for this amazing video on spring security and CORS, Dan! This video helped a lot.
Thanks Dan ! Its so informative videos for cors and spring security.
You are welcome! I am glad these videos on Spring Security are helping out.
Dan, thanks for the video. You saved my life!
You are a life saver Dan
You saved my day and explained very well by covered up all the scenario !
Thanks for the video Dan, it helped me a lot with my CORS implementation.
thanks Dan
thank you so much for this!
Thanks Dan!
Thank you, Fernando.
awesome tutorial, as always! ☺️
It's worked. Thank you so much for the assist.
Thanks for sharing your knowledge, Dan! This helped out A LOT.
How would you go about configuring CORS when your vue app needs to authenticate against a spring boot app using an external auth provider like Google's OAuth2?
It would be great to see a video covering this topic! Any chance we see this at some point? :)
Thanks for the suggestion github.com/danvega/office-hours/discussions/33
Thanks so much for this video. It absolutely explained what I needed
Great video, thanks for share your knowledge
Glad it was helpful Javier!
Great tutorial
Thank you! Cheers!
Fan of your videos
Thank you so much for watching!
Thank you so much! You helped a lot!
Really good thanks Dan!
My pleasure!
I want to thank you from heart for all the efforts you put to explain such useful concepts
very useful!!
thanks
you save my night!
Dan, I was really confuse with cors and Spring Security, the documentation isn't that good like your explanation, documentation skipped an important step that gave me an error that you solved. My english is very very basic, but i wanted to thank you, cheers from Colombia!
Thanks
at 21:07 - if you get an error 401 and an empty json response: check if you used the same username and password at SecurityConfig InMemoryUserDetailsManager users() (see 16:26)
Thank u
Thanks for the tutorial but this doesn't work for me I've tried CorsFilter and it works for me.
at 15:54 - i got a "cannot resolve spring-boot-starter-security 2.7.4" - fix for me was to add `2.7.3`
It worked for me. But another issue i've :- I'm using microservices and direct call from UI to service is ok
But whn I tried to call through api gateway then again I'm getting CORS error
Please help me here, whether I need to configure anything in api gateway level also ??
May I know at 20:57, where did you get this Authorization: "Basic ZHZlZ2E6cGFzc3dvcmQ=" from?
Hello Dan. Thank you for sharing your knowledge. I have a question. Can I have two configurations for two different endpoints?
Example:
CorsConfiguration clientConfig = new CorsConfiguration);
CorsConfiguration adminConfig = new CorsConfiguration);
source. registerCorsConfiguration ("/client/**", clientConfig);
source. registerCorsConfiguration ("/admin/**", adminConfig);
return source;
Thank you in advance for your time.
Didn't work for me! Fixed.
I'm working on the new authorization server and created a very simple static frontend(only for testing purposes) and it didn't work for me.
In this flow we're using two filterChains. One for the authorization and one default on top of that. Of course i needed to add the same CORS-policy in both filterchains.
So yeah, if you for any reasons have multiple filterchains, dont forget to add CORS to both.
Btw Dan, your videos are really really good. They are so much shorter than most videos which makes it easy to use them for reference. Not only that, the content is perfectly balances.
Would u pls give example code snippet on how to add cors to two filter chains
sir i am having problem while routing with gateway . suppose my gateway is 8085 and api is in 8082 so calling the api though 8085 giving cors problem
It's not working for me
What's not working?
still i am getting the cors error, my preflight request is getting 403 error
Hello sir, i just want to ask you that my application is working fine on my pc having react as frontend and spring boot as backend, but when I am using my ipv4 to see my application on my chrome browser on Android device, the data from the backend are not visible. Connection refused. Please help me🙏
in 21:19 how did we get the Authorization information in the fetch header part? I guess when we do mvn verify it should give this code in the console. Am I wrong?
I did everyone's implementation nothing works for me 😢
ERR_CONNECTION_REFUSED I got this error i could not understand why?
I would need some more information. Did you build this from scratch or clone the repo? What are you doing to produce this error?
How about the dsl version? Do you specify the pattern /** there?
Hello Dan. Thank you for the video. Could you please explain about .setAllowedHeaders("Authorization")? What does it do, when is it needed? I actually tested my oauth2 client application without this line and authorization still works fine.
It might be that your oauth2 client uses a session cookie for authorization instead of the 'Authorization' header. In that case the Authorization header (which contains a Bearer token) is not needed and allowing or disallowing that header would have no effect. Hope this helps.
Hi it did not work for me, does this solution supports spring boot 3 & spring security 6
My application already had a @WebFilter class, to handle authorization. I have added your global CORs WebSecurityConfig code and no longer getting CORs errors on requests but requests never seem to reach the existing Webfilter after this CORs filter, so all requests are failing with 401. Any ideas?
How you resolved this problem?
I am still getting blocked by CORS :(
Are you specifying the correct port? Are you sending any specific headers?
@@DanVega Thanks for the quick answer Dan. This is what i did : i was following along first. But since it didn't work (the last part with spring-security involved) i copy the whole SecurityConfig class, just changed the username for the InMemoryUser. For the frontend part i just copied paste the folder, no change. Note that i deleted the WebMvcConfig as well so it's not that
Man you should make some courses in Udemy or uploading your videos in Udemy so the people that dont like giving youtube money can support you
Even its not working
It doesn't work.
What issues are you having? Can you send me a repo with the issue you're facing and I will see if I can take a look at it
@DanVega
For some reason I couldnt make your solution to work out for me... It worked up until the part with spring security. However I added a part in the config and it sorted it out. . I wonder thou if this is considered best practise or even working in general?
I added this to the SecurityFilterChain class
.addFilterBefore(corsFilter(), CsrfFilter.class)
and modified your CorsConfigurationSource to this instead:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("localhost:3000"));
config.setAllowedMethods(Arrays.asList("GET", "POST"));
config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
I have a react application that connects the the spring boot, I used your modification and it worked for me.
in the video , there is no config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type")); as it been sent using cookies but I think in our case we need to add this so spring understand what headers are allowed.
this is what I understand from both solution, I might be mistaked, so please elaborate if you have the knowledge or anyone can do so
Anywas , thank you all for your efforts.
Great tutorial would like to add one little thing to it though. Code for global cors won't work if you don't add following line in addCorsMapping function:
WebMvcConfigurer.super.addCorsMappings(registry);
After adding mappings to registry you need to provide CorsRegistry object to WebMvcConfigurer.super.addCorsMappings to make things work. Keep up the good work bro.