Solution of the Cors Error From a Spring Boot and Angular Application
Вставка
- Опубліковано 6 лип 2024
- In this video I show how to solve the CORS error which appears at every project. I show the resolution in a Spring Boot and Angular project. I describe the problem itself and multiple options to solve it.
The CORS error appears when a frontend tries to access a backend with a different URL. To solve this problem, I must configure my backend to accept a frontend from a different URL. I can also specify which HTTP methods are accepted and which HTTP Headers.
The CORS error doesn't appear when both the frontend and the backend are at the same URL. This happens with a frontend deserved from a Spring Boot application. I show this behavior in the Chapter "Same Origin".
This video belongs to a playlist where I develop fullstack applications using a frontend and a backend in Spring Boot: • How to Easily Secure Y...
Chapters:
0:00:00 Introduction
0:02:03 Backend Creation
0:04:05 Frontend Creation
0:07:01 Same Origin
0:09:30 Annotation
0:10:04 Cors configuration
My NEW eBook: sergiolema.dev/git-book/
Github project: github.com/serlesen/fullstack...
Blog: bit.ly/47ornJL
LinkedIn: bit.ly/41Nn61q
Facebook: bit.ly/47rc9nh
My Desktop:
• Laptop: Macbook Pro 16' 2019
• Gaming Chair: amzn.to/47Vu6ed
• Mouse: amzn.to/3HoBwM1
• Desk: amzn.to/48Tc5Oi
• Screen: amzn.to/48VZkCL - Наука та технологія
After dozens of tutorials/articles... this one helped me! I lost like 30 hours on this issue :D thank you
I so happy for you Krzysiek!
Sergio, super conciso y directo al grano, gracias
Gracias a ti por el comentario!
Been following your channel and I absolutely love your content. Been also building my own backend app using some of your code as well (you're my springboot stackoverflow lol). Security is the only part that still tends to confuse me with springboot, and I'm yet to learn spring cloud.
Thank you so much! I'm glad to know you learned this much and you're able to build your own backend. About Spring Security, did you check my playlist about it? I know it's hard, but try to watch many videos, I explain it in different ways, maybe you findone easy to understand
Thank you a lot! ♥ I've been trying to solve this for an hour.
Good job!
Excelente!! Nos salvaste hermano, teníamos ese problema con una aplicación Angular / Spring boot desplegada en AWS con Beanstalk, habíamos probado otras soluciones pero esta fue la definitiva. ¡Muchas gracias!
Encantado! Una vez que encuentras una solución sencilla, parece evidente, pero hasta encontrarla se sufre 😅
Thanks for the explaination!
I'm happy it helped you!
It works
Thank for sharing!!❤
Thanks for watching!
I LOVE YOU FOR THIS!!!!
Glad it helped you this much!
Muchas gracias. Gran vídeo.
Gracias a ti por el comentario!
Awesome content on spring boot
Thank you!
Nice video! Another solution would be to keep both back and front behind a gateway so all calls go throught same domain and no cors config needed
That could be a solution. But if I keep my frontend behind a gateway, I can't take advantage of a CDN.
Tengo una duda, Sergio. El script que escribes en aprox. 7:43 ¿es necesario mantenerlo también o sólo es para demostrar lo que ocurre en ese momento en concreto?
En mi caso, en lugar de configurar addCorsMappings en Spring lo que he hecho ha sido configurar un proxy en Angular, y así sí me ha funcionado.
Un saludo.
Es solo para demostrar el comportamiento con llamadas en AJAX.
La solución en Angular también es acceptable, pero estarías "engañando" al backend haciéndole pensar que las llamadas vienen de él.
@@TheDevWorldbySergioLema Sí, justo. Gracias por responder, Sergio. Ya he quitado el proxy, pero en mi caso es complicado porque se trata de un backend con Spring que además autentifica con un Single-Sign-On que realiza una redirección a un servidor CAS y por eso estoy teniendo problemas. ¡Muchas gracias y un saludo!
Hi, Thanks for your video. Would you kindly share what you would do in different environments? stages?
I add the different URLs allowedOrigins method. As this method accepts a list of Strings, I can add all the URLs of my environments.
Thank you for this video
I'm glad it helped you!
Hola, es necesario tener en la clase SecurityConfig el .cors(Customizer.withDefaults()) , si ya he creado una clase CorsConfig dónde manejo de manera global los cors?
En un video que estoy acabando de realizar (en 5 o 10 días) trato el error CORS cuando tienes Spring Security.
Y la respuesta es: si, necesitas indicarle a Spring Security que has configurado los CORS.
Thank you, mate
Glad it helped you!
Excellent
Thanks!
Thanks it helped
You're welcome
Can use http header to configure or solve the CORS error in Angular?
The CORS problem should be solved in the backend. Hijacking the CORS with the headers is another solution, but this is trying to fake the browser and the backend.
Excellent, Could you please provide a video tutorial on configuring CSRF attack prevention using spring security 6 and React.js in an upcoming video.
That was exactly what I'm working on. I hope it will be ready for mi-Octobre.
would that work when using spring security?
When using Spring Security, it's recommended using filters, check this other video, ua-cam.com/video/phs90_s0Mjk/v-deo.html
I have a doubt, when I try to use interceptors to save the login token I get again the headers blocking, is there a solution? I use spring boot 3 angular 16
You need to accept the headers in the CORS configuration. What interceptors are you talking about? It's the Spring HTTP Filters?
@@TheDevWorldbySergioLema I solved it, the problem was that in the propierties of the app I had it in create-drop for some reason spring security does not detect the CORS configuration when it is like that, I put it in update and now it works.
I'm not sure to understand. Spring Security has nothing to do with CORS or the schema validation. The schema validation is done with Spring JPA (which has nothing to do with the CORS of Spring Web)...
Still, if the problem is solved, it's solved!
i did the same thing what you shown in video, but still i am getting the same error why? can you please help me
Did you add the correct frontend URL? Sometimes, Spring Boot (and Spring Security) throws an error saying the CORS issue, but in fact the problem is somewhere else. Try to add an exception handler to see if that's the case. Do you have any authentication system?
i was tested your Project on the linux Server, i didn't got the greeting message from the backend because of cors!!!
Message received from the backend
empty
I just check the projet, it works fine on MacOS. Do you have any error?
@@TheDevWorldbySergioLema
Thank you very much to your Feedback!!!
yes!
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at my ip adresse/greetings. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
@@TheDevWorldbySergioLema
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at my ip adresse/greetings. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
thanks !
Thanks to you Yasine for watching!
It doesn’t work still appear to me core origin error when i make request from my local web browser can you help me to solve it ?
What error do you have? Does it work from a terminal or Postman?
Do you have Spring Security enabled in the backend?
@@TheDevWorldbySergioLema yes I’m enabling spring security
thanks a lot
Glad it helped you Mahmudul! (I had no time to answer to your previous comment, and I see you edit it 😅, good to know you found the solution)
@@TheDevWorldbySergioLema previously created a class for dto that's why it was not working. after I changed it to record now it works
Awesome content!
Thank you Adrian!
nice mano me salvou
I'm happy for you Matheus!
Perfect
Thank you Leandro!
@@TheDevWorldbySergioLema I'm new to spring boot, and this helped me a lot
I'm glad to here that. If you're looking for more knowledge about Spring Boot, I have a playlist which builds a complete backend. And if you're looking for personal coaching, take a look at my Academy (look in the description of the video)
@@TheDevWorldbySergioLemaThank you
not helpful, cause i have added cors * to my spring boot application, but the problem is still same.
Oh, I'm sorry. Do you have Spring security in your application?
Check this alternative: ua-cam.com/video/phs90_s0Mjk/v-deo.html
sadly this doesnt work for my react app (microsoft teams application)
You have a React application running under Microsoft Teams?
I'm not sure to understand your comment
When working with Spring Security, you need this other solution: ua-cam.com/video/phs90_s0Mjk/v-deo.html
@TheDevWorldbySergioLema I’ll try it right now, if this works man… 😭😭. I ll let u know
it workd@@TheDevWorldbySergioLema
But i need to validate my jwt with spring.cloud.azure.active-directory and spring.security.oauth2.resourceserver.jwt etc
can i post a small 2 class repository link on my github so u knwo what im talking about. because the cors problem is succesfully gone
but the way i validate my token doesnt work in newer verrsions of spring 3+ (i used 2.7.5)
This problem seems very specific to your version of spring and Azur. I don't think I can't help you much.
sir it's not spring security. kindly solve the issue with spring security
The CORS problems appears in the Spring Boot Web dependency. No need to have Spring Security.
If you add the Spring Security dependency, it can be solved the same way.
@@TheDevWorldbySergioLema i have set CORS in gateway and there is no need to use CORS anywhere in all other MS . working fine for me . i need to know about it am i right?
If you use Microservices, the CORS should only be configured in the Gateway, you're right.
It doesn't work.
I'm sorry to hear that. Do you have an error which describes your problem?
@@TheDevWorldbySergioLema Only the same error I get when there's no @CrossOrigin at all. I have since making the comment found that making it @CrossOrigin(origins = "*") works, but trying to put the actual URL of the site that should connect to the API does not work at all.
Do you see the correct headers in the OPTIONS request when adding CrossOrigin with your URL?