IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Spring Boot Java Discussion :

probleme de cors origin


Sujet :

Spring Boot Java

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Juillet 2023
    Messages
    4
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Chercheur en informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2023
    Messages : 4
    Points : 1
    Points
    1
    Par défaut probleme de cors origin
    Bonjour à tous
    J'ai un probleme de cors origin en essayant d'appeler mes API backend depuis le front angular
    Mon back tourne sur le port 4000 (application spring boot 2.7.5)

    J'ai pourtant tenté deux choses : Mettre @CrossOrigin(origins = "*")

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @RestController
    @RequestMapping(path = "/professionnel")
    @CrossOrigin(origins = "*")
    public class ProfessionnelControler {
     
      Logger logger = LoggerFactory.getLogger(ProfessionnelControler.class);
      ProfessionnelRepository professionnelRepository;
      ProfessionnelService professionnelService;
     
      @GetMapping("/all")
      public List<Professionnel> getAllProfessionnel() {
        return (List<Professionnel>) professionnelRepository.findAll();
      }
    et j'ai tenté aussi avec une classe de configuration
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @Configuration
      @EnableWebMvc
      public class Config implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
          registry.addMapping("/**")
              .allowedOrigins("http://localhost:4200") // meme avec le * ça ne donne rien
              .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
              .allowedHeaders("*")
              .allowCredentials(true);
        }
      }
    Voici ce que j'obtient coté front au niveau du navigateur
    Access to XMLHttpRequest at 'http://localhost:4000/professionnel/all' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
    L'appel depuis postman fonctionne

    Merci de e votre aide je galère depuis des semaines .

  2. #2
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    C'est effectivement assez chiant.

    Le mieux est d'injecter un bean gérant ça dans le contexte Spring.
    Dans mon projet:
    https://bitbucket.org/philippegibaul...iguration.java

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
     
    package com.calculateur.warhammer.rest.configuration.general;
     
    import java.util.Arrays;
     
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
     
    /**
     * Configuration pour les service REST pour Spring Boot
     * @author phili
     *
     */
    @ComponentScan(basePackages = {"com.calculateur.warhammer.rest.controller"})
    public class AbstractRestConfiguration implements WebMvcConfigurer{
     
    	@Value("${clientWeb}")
    	private String clientWeb;
     
    	@Bean("securityFilterChain")
    	public SecurityFilterChain getFilterChain(HttpSecurity http) throws Exception {
    			return http
    				.cors().configurationSource(getCorsConfigurationSource())
    					.and()
    				.csrf().disable()	
    				.build();
    	}
     
    	@Bean("corsConfigurationSource")
    	public CorsConfigurationSource getCorsConfigurationSource() {
    		CorsConfiguration configuration = new CorsConfiguration();
    		configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    		configuration.applyPermitDefaultValues();
    		configuration.addAllowedOrigin(clientWeb);
    		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    		source.registerCorsConfiguration("/**", configuration);
    		return source;
    	}	
    }
    Le mieux est de laisser tout le monde venir (il y a d'autre méthodes pour empêcher un utilisateur d'utiliser un service REST).

    La valeur est donc "*".

    Je l'ai injecté via Docker dans le docker compose:
    https://bitbucket.org/philippegibaul...er-compose.yml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
     
    version: '3.7'
    services:
       db:
          container_name: db
          networks:
             - networks-warhammer-database
          image: postgres:10.5
          restart: always
          environment:
             - POSTGRES_USER=${DATABASE_LOGIN}
             - POSTGRES_PASSWORD=${DATABASE_PASSWORD}
          logging:
             options:
                max-size: 10m
                max-file: "3"
          ports:
             - '5432:5432'
          expose:
             - "5432"   
          volumes:
             - ./postgres-data:/var/lib/postgresql/data
          healthcheck:
             test: ["CMD-SHELL", "pg_isready -U postgres"]
             interval: 5s
             timeout: 5s
             retries: 5
       install_db:
          container_name: warhammer-database-install
          build:
             context: ./creation_database
             args:
                - ARGS_INSTALLATION='databaseHost=db loginDatabase=${DATABASE_LOGIN} passwordDatabase=${DATABASE_PASSWORD} portDatabase=5432 databaseName=warhammer
          networks:
             - networks-warhammer-database
          depends_on:
             db:
                condition: service_healthy
       warhammer_back:
          container_name: warhammer_back
          restart: always
          ports:
             - '8080:8080'
          build:
             context: ./rest
          environment:
                - databaseHost=db
                - loginDatabase=${DATABASE_LOGIN}
                - passwordDatabase=${DATABASE_PASSWORD}
                - portDatabase=5432
                - databaseName=warhammer 
                - databaseProperties='loglevel=2
                - isShowSQL=false
                - clientWeb=*
          networks:
             - networks-warhammer-database
             - networks-warhammer-back
          depends_on:
             db:
                condition: service_healthy 
       warhammer_front:
          container_name: warhammer_front
          restart: always
          ports:
             - '80:80'
          build:
             context: ./client_angular  
          networks:
              - networks-warhammer-back   
          depends_on:
             - warhammer_back
    networks:
       networks-warhammer-database:
          external: true
       networks-warhammer-back:
          external: true

  3. #3
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    Ceci se fait en utilisant Spring Security.

  4. #4
    Nouveau Candidat au Club
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Juillet 2023
    Messages
    4
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Chercheur en informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2023
    Messages : 4
    Points : 1
    Points
    1
    Par défaut
    Merci Philippe par contre ça ne marche pas chez moi
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    package com.candle.devisarchi.config;
     
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import java.util.Arrays;
     
    @ComponentScan(basePackages = {"com.candle.devisarchi.controler"})
    public class Conconf implements WebMvcConfigurer {
     
     
      @Bean("securityFilterChain")
      public SecurityFilterChain getFilterChain(HttpSecurity http) throws Exception {
        return http
            .cors().configurationSource(getCorsConfigurationSource())
            .and()
            .csrf().disable()
            .build();
      }
     
      @Bean("corsConfigurationSource")
      public CorsConfigurationSource getCorsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.applyPermitDefaultValues();
        configuration.addAllowedOrigin("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
      }
    }

  5. #5
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    Là, il faudrait donner le message d'erreur.

  6. #6
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    Ma classe est un template Method, dans l'implémentation de base, il faut @EnableWebMvc soit:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
     
    package com.calculateur.warhammer.rest.configuration;
     
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
     
    import com.calculateur.warhammer.rest.configuration.general.AbstractRestConfiguration;
    import com.calculateur.warhammer.service.configuration.ConfigurationService;
     
    /**
     * Configuration REST pour la PROD
     * @author phili
     *
     */
    @Configuration
    @EnableWebMvc
    @Import(value = {ConfigurationService.class})
    public class RestConfiguration extends AbstractRestConfiguration{
     
    }
    https://bitbucket.org/philippegibaul...iguration.java

  7. #7
    Nouveau Candidat au Club
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Juillet 2023
    Messages
    4
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Chercheur en informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2023
    Messages : 4
    Points : 1
    Points
    1
    Par défaut
    Merci Philippe
    J'ai rajouté l'annotation @enableWebMvc

    et j'ai toujours l'erreur
    /*********************************
    Access to XMLHttpRequest at 'http://localhost:4000/professionnel/all' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
    /*************************************


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    package com.candle.devisarchi.config;
    
    import org.hibernate.engine.config.spi.ConfigurationService;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Import;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import java.util.Arrays;
    
    @ComponentScan(basePackages = {"com.candle.devisarchi.controler"})
    @EnableWebMvc
    @Import(value = {ConfigurationService.class})
    public class Conconf implements WebMvcConfigurer {
    
    
      @Bean("securityFilterChain")
      public SecurityFilterChain getFilterChain(HttpSecurity http) throws Exception {
        return http
            .cors().configurationSource(getCorsConfigurationSource())
            .and()
            .csrf().disable()
            .build();
      }
    
      @Bean("corsConfigurationSource")
      public CorsConfigurationSource getCorsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.applyPermitDefaultValues();
        configuration.addAllowedOrigin("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
      }
    }
    merci de ton aide

  8. #8
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    Je pense que là, c'est plutôt côté Javascript.

  9. #9
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    Si le controller Java a encore @CrossOrigin(origins = "*"), ce n'est plus nécessaire.

    Peux-tu montrer le controlleur et la classe de configuration?

  10. #10
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5

  11. #11
    Nouveau Candidat au Club
    Homme Profil pro
    Chercheur en informatique
    Inscrit en
    Juillet 2023
    Messages
    4
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Chercheur en informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2023
    Messages : 4
    Points : 1
    Points
    1
    Par défaut
    Voilà le controler


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    @RestController
    @RequestMapping(path = "/professionnel")
    public class ProfessionnelControler {
     
      Logger logger = LoggerFactory.getLogger(ProfessionnelControler.class);
      ProfessionnelRepository professionnelRepository;
      ProfessionnelService professionnelService;
     
      @GetMapping("/all")
      public List<Professionnel> getAllProfessionnel() {
        return (List<Professionnel>) professionnelRepository.findAll();
      }
     
     
      public ProfessionnelControler(ProfessionnelRepository professionnelRepository, ProfessionnelService professionnelService) {
        this.professionnelRepository = professionnelRepository;
        this.professionnelService = professionnelService;
      }
      @PostMapping("/create")
      public ResponseEntity createlProfessionnel(@RequestBody Professionnel professionnel) {
        try {
          professionnelRepository.save(professionnel);
          logger.info("Le professionne a été rajoutée " + professionnel);
     
          return ResponseEntity.status(HttpStatus.OK).body("appel ok");
        } catch (Exception e) {
          logger.warn("Erreur lors de la tentative de création d'un professionne" + professionnel.toString());
          return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("erreur interne");
        }
      }

  12. #12
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    462
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 462
    Points : 896
    Points
    896
    Billets dans le blog
    5
    Par défaut
    Je pense que le problème est côté Angular. Mais là, je ne sais plus comment faire.

  13. #13
    Modérateur
    Avatar de kolodz
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2008
    Messages
    2 211
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 211
    Points : 8 316
    Points
    8 316
    Billets dans le blog
    52
    Par défaut
    Bonjour,

    Pense à regarder le message spécifique retournée dans ton navigateur.
    Si tu regarde l'appel dans la partie Réseau, tu devrai voir des valeurs dans le header de la réponse de ton serveur qui corresponds au AllowOrigin (Genre Access-Control-Allow-Origin)
    Donc à vérifier si les solutions proposés avant ont bien l’impacte voulu (ajouté le bon header)


    Personnellement, j'ai constaté que certains navigateur commence à bloquer la valeur "*" et demande d'expliciter les valeurs proprement. (dans ton cas localhost:4200 si j'ai bien suivi)

    Sinon, une solution temporaire et local est de désactivé la sécurité cros de ton navigateur de développement.

    Source :
    https://developer.mozilla.org/fr/docs/Web/HTTP/CORS
    Si une réponse vous a été utile pensez à
    Si vous avez eu la réponse à votre question, marquez votre discussion
    Pensez aux FAQs et aux tutoriels et cours.

Discussions similaires

  1. Erreur Accès CORS Access-Control-Allow-Origin
    Par angie13003 dans le forum Angular
    Réponses: 1
    Dernier message: 10/05/2021, 19h44
  2. ReactJs Ajax cors-origin
    Par Sparky95 dans le forum React
    Réponses: 2
    Dernier message: 08/10/2020, 18h44
  3. Json et CORS (Cross-Origin resource sharing)
    Par Olmer dans le forum Web & réseau
    Réponses: 2
    Dernier message: 19/08/2015, 18h53
  4. Réponses: 4
    Dernier message: 10/09/2014, 16h04
  5. [FLASH 8] Probleme d'origine je pense
    Par bibile dans le forum ActionScript 1 & ActionScript 2
    Réponses: 6
    Dernier message: 16/01/2007, 13h04

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo