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
  • Наука та технологія

КОМЕНТАРІ • 94

  • @krzysiekdzioba293
    @krzysiekdzioba293 5 місяців тому +6

    After dozens of tutorials/articles... this one helped me! I lost like 30 hours on this issue :D thank you

  • @col_yom
    @col_yom 10 місяців тому

    Sergio, super conciso y directo al grano, gracias

  • @thendoronnyramashia749
    @thendoronnyramashia749 10 місяців тому

    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.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  10 місяців тому

      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

  • @vahdettinokur9978
    @vahdettinokur9978 5 місяців тому

    Thank you a lot! ♥ I've been trying to solve this for an hour.

  • @alejandrorussifajardo9739
    @alejandrorussifajardo9739 7 місяців тому

    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!

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  7 місяців тому

      Encantado! Una vez que encuentras una solución sencilla, parece evidente, pero hasta encontrarla se sufre 😅

  • @thuanquoc1231
    @thuanquoc1231 3 місяці тому

    Thanks for the explaination!

  • @aniketpatil2429
    @aniketpatil2429 Місяць тому

    It works
    Thank for sharing!!❤

  • @SherryVids143
    @SherryVids143 4 місяці тому

    I LOVE YOU FOR THIS!!!!

  • @krait7188
    @krait7188 4 місяці тому

    Muchas gracias. Gran vídeo.

  • @vikashmishra3461
    @vikashmishra3461 10 місяців тому

    Awesome content on spring boot

  • @murilo.g.t
    @murilo.g.t 10 місяців тому +1

    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

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  10 місяців тому

      That could be a solution. But if I keep my frontend behind a gateway, I can't take advantage of a CDN.

  • @conatcha
    @conatcha 7 місяців тому

    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.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  7 місяців тому +1

      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.

    • @conatcha
      @conatcha 7 місяців тому +1

      @@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!

  • @kojo_ampia
    @kojo_ampia 4 місяці тому

    Hi, Thanks for your video. Would you kindly share what you would do in different environments? stages?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  4 місяці тому

      I add the different URLs allowedOrigins method. As this method accepts a list of Strings, I can add all the URLs of my environments.

  • @akhilsnair1488
    @akhilsnair1488 5 місяців тому

    Thank you for this video

  • @andyrojas7518
    @andyrojas7518 5 місяців тому

    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?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  5 місяців тому

      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.

  • @madalinaionescu802
    @madalinaionescu802 4 місяці тому

    Thank you, mate

  • @user-ih4th8ob7p
    @user-ih4th8ob7p 10 місяців тому

    Excellent

  • @ashwinkumar504
    @ashwinkumar504 Місяць тому

    Thanks it helped

  • @weixiangng8279
    @weixiangng8279 4 місяці тому

    Can use http header to configure or solve the CORS error in Angular?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  3 місяці тому

      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.

  • @MirwaisFaizi786
    @MirwaisFaizi786 10 місяців тому

    Excellent, Could you please provide a video tutorial on configuring CSRF attack prevention using spring security 6 and React.js in an upcoming video.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  10 місяців тому

      That was exactly what I'm working on. I hope it will be ready for mi-Octobre.

  • @lachezarmitov6628
    @lachezarmitov6628 3 місяці тому

    would that work when using spring security?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  3 місяці тому +1

      When using Spring Security, it's recommended using filters, check this other video, ua-cam.com/video/phs90_s0Mjk/v-deo.html

  • @juancordova2464
    @juancordova2464 9 місяців тому

    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

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  9 місяців тому +1

      You need to accept the headers in the CORS configuration. What interceptors are you talking about? It's the Spring HTTP Filters?

    • @juancordova2464
      @juancordova2464 9 місяців тому

      @@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.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  9 місяців тому

      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!

  • @pradeepk2864
    @pradeepk2864 8 місяців тому

    i did the same thing what you shown in video, but still i am getting the same error why? can you please help me

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  8 місяців тому

      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?

  • @AraSali-oe6qr
    @AraSali-oe6qr 9 місяців тому

    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

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  9 місяців тому

      I just check the projet, it works fine on MacOS. Do you have any error?

    • @arazali3179
      @arazali3179 9 місяців тому

      @@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)

    • @AraSali-oe6qr
      @AraSali-oe6qr 9 місяців тому

      @@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)

  • @yassinebengharsallah4258
    @yassinebengharsallah4258 10 місяців тому

    thanks !

  • @marwansameer8255
    @marwansameer8255 Місяць тому

    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 ?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Місяць тому

      What error do you have? Does it work from a terminal or Postman?
      Do you have Spring Security enabled in the backend?

    • @marwansameer8255
      @marwansameer8255 Місяць тому

      @@TheDevWorldbySergioLema yes I’m enabling spring security

  • @Mahmudulhasan-ts5hm
    @Mahmudulhasan-ts5hm 7 місяців тому

    thanks a lot

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  7 місяців тому

      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)

    • @Mahmudulhasan-ts5hm
      @Mahmudulhasan-ts5hm 7 місяців тому +1

      @@TheDevWorldbySergioLema previously created a class for dto that's why it was not working. after I changed it to record now it works

  • @adrian333dev
    @adrian333dev 10 місяців тому

    Awesome content!

  • @hadens1923
    @hadens1923 5 місяців тому

    nice mano me salvou

  • @leandrocruz6621
    @leandrocruz6621 6 місяців тому

    Perfect

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  6 місяців тому +1

      Thank you Leandro!

    • @leandrocruz6621
      @leandrocruz6621 6 місяців тому

      @@TheDevWorldbySergioLema I'm new to spring boot, and this helped me a lot

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  6 місяців тому +1

      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)

    • @leandrocruz6621
      @leandrocruz6621 6 місяців тому

      ​@@TheDevWorldbySergioLemaThank you

  • @wanderingearth8217
    @wanderingearth8217 5 місяців тому

    not helpful, cause i have added cors * to my spring boot application, but the problem is still same.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  5 місяців тому

      Oh, I'm sorry. Do you have Spring security in your application?
      Check this alternative: ua-cam.com/video/phs90_s0Mjk/v-deo.html

  • @QSC3
    @QSC3 3 місяці тому

    sadly this doesnt work for my react app (microsoft teams application)

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  3 місяці тому

      You have a React application running under Microsoft Teams?
      I'm not sure to understand your comment

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  3 місяці тому

      When working with Spring Security, you need this other solution: ua-cam.com/video/phs90_s0Mjk/v-deo.html

    • @QSC3
      @QSC3 3 місяці тому +1

      @TheDevWorldbySergioLema I’ll try it right now, if this works man… 😭😭. I ll let u know

    • @QSC3
      @QSC3 3 місяці тому

      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)

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  3 місяці тому

      This problem seems very specific to your version of spring and Azur. I don't think I can't help you much.

  • @hkkabir2024
    @hkkabir2024 6 місяців тому

    sir it's not spring security. kindly solve the issue with spring security

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  6 місяців тому

      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.

    • @hkkabir2024
      @hkkabir2024 6 місяців тому

      @@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?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  6 місяців тому

      If you use Microservices, the CORS should only be configured in the Gateway, you're right.

  • @92nicu17
    @92nicu17 3 місяці тому

    It doesn't work.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  3 місяці тому

      I'm sorry to hear that. Do you have an error which describes your problem?

    • @92nicu17
      @92nicu17 3 місяці тому

      @@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.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  3 місяці тому

      Do you see the correct headers in the OPTIONS request when adding CrossOrigin with your URL?