WillGates
WillGates

Reputation: 75

Spring Boot: Cors policy missing 'access-control-allow-origin'

Error: I get the following in Firefox: Foreign Site Query Blocked: The same origin policy does not allow reading of the remote resource http: // localhost: 8080 / api / v1 / post /. (Cause: The 'Access-Control-Allow-Origin' CORS header does not exist)

I have spent several hours to allow CORS communication with my Spring Boot server in order to make my REACT UI communicate with the server. There are lot of similarly phrased questions on Stack Overflow, but non of the suggested solutions have solved my problem...

Spring Boot suggests different solutions on https://spring.io/guides/gs/rest-service-cors/. One local solution is using annotations. A global solution can be obtained with a config file.

I have tried annotating the controller with @CrossOrigin as seen in my code below:

package com.example.Blogging.api;

import com.example.Blogging.model.Post;
import com.example.Blogging.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.UUID;


@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping("api/v1/post")
@RestController
public class PostController {

    private final PostService postService;

    @Autowired
    public PostController(PostService postService) {
        this.postService = postService;
    }


    @PostMapping
    public void addPost(@RequestBody Post post){
        postService.addPost(post);

    }

    @GetMapping
    public List<Post> getAllPosts(){
        return postService.getAllPosts();

    }

    @GetMapping(path = "{id}")
    public Optional<Post> getPostById(@PathVariable("id") UUID id){
        return postService.getPostById(id);

    }

    @PutMapping(path="{id}")
    public void updatePostById(@PathVariable("id") UUID id, @RequestBody Post post){
        postService.updatePost(id,post);
    }


    @DeleteMapping(path="{id}")
    public void deletePostById(@PathVariable("id") UUID id){
        postService.deletePost(id);
    }


}

This did not work.. I have also tried annotating on each method instead of the whole controller class.

Furthermore I have tried to make a config file:

package com.example.Blogging.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("*");
    }
}

Nothing really seems to work. The console in my browser keeps saying 'access-control-allow-origin' is missing in the response header..

For reference, I will also put my pom.xml below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>Blogging</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Blogging</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>



        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- SPRING SECURITY -->
        <!--<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <scope>test</scope>
        </dependency>-->



        <!-- SPRING BOOT STARTER SECURITY -->
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>

        </plugins>
    </build>

</project>

Anyone who can suggest a solution? Thank you in advance!

Upvotes: 3

Views: 9303

Answers (1)

Joker
Joker

Reputation: 2463

I just noticed, you have Spring Security in your dependencies. You might missed to enable CORS in your WebSecurityConfig.

Eg. something like this:

@EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and()...
        }
    }

Upvotes: 3

Related Questions