Problems in setting up CORS Spring Boot!

1

This is the error message you are giving;

I'mhavingahardtimemakingmyFrontEndAPIhavepermissiontoaccessmyBack-EndAPIwhichisaSpringBootproject,I'msuremyproblemisnotmyFron-EndAPI,theproblemisintheconfigurationoftheCORSregardingaccesspermission.

I'llleavemyCORSconfigurationrightbelow

import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import br.com.mdw.config.MdwApiProperty; @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { @Autowired private MdwApiProperty mdwApiProperty; @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; response.setHeader("Access-Control-Allow-Origin", mdwApiProperty.getOriginPermitida()); response.setHeader("Access-Control-Allow-Credentials", "true"); if ("OPTIONS".equals(request.getMethod()) && mdwApiProperty.getOriginPermitida().equals(request.getHeader("Origin"))) { response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS"); response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept"); response.setHeader("Access-Control-Max-Age", "3600"); response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, resp); } } @Override public void destroy() { } @Override public void init(FilterConfig arg0) throws ServletException { } }

And here where I set up access:

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("mdw")
public class MdwApiProperty {

    private String originPermitida = "http://localhost:8000";

    private final Seguranca seguranca = new Seguranca();

    public Seguranca getSeguranca() {
        return seguranca;
    }

    public String getOriginPermitida() {
        return originPermitida;
    }

    public void setOriginPermitida(String originPermitida) {
        this.originPermitida = originPermitida;
    }

    public static class Seguranca {

        private boolean enableHttps;

        public boolean isEnableHttps() {
            return enableHttps;
        }

        public void setEnableHttps(boolean enableHttps) {
            this.enableHttps = enableHttps;
        }

}


}

A class called MdwApiProperty

Where the following annotation was placed:

@ConfigurationProperties("mdw")

And because of this annotation, that's why the application-prod.properties file accepted this line of code.

mdw.seguranca.enable-https=true

If this is true if I happen to modify the MdwApiProperty class annotation for

@ConfigurationProperties("habilitando-producao")

Iria looks like this in the application-prod.properties file.

habilitando-producao.seguranca.enable-https=true

And in these files where the nickname for project access is enabled

package br.com.mdw;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import br.com.mdw.config.MdwApiProperty;

@SpringBootApplication
@EnableConfigurationProperties(MdwApiProperty.class)
public class MdwApplication {

    public static void main(String[] args) {
        SpringApplication.run(MdwApplication.class, args);
    }
}

This is where the annotation is

mdw.seguranca.enable-https=true spring.datasource.url={JDBC_DATABASE_URL} spring.datasource.username={JDBC_DATABASE_USERNAME} spring.datasource.password={JDBC_DATABASE_PASSWORD} mdw.origin-permitida=https://mdw-arm-wladimir.herokuapp.com

For some reason he is not accepting access, I need help.

    
asked by anonymous 11.03.2018 / 09:46

1 answer

2

Disables your CORs implementation of SPRING and tries to use one of these 2 (two) solutions:

Solution 1:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import com.example.algamoney.api.config.property.AlgamoneyApiProperty;

@Configuration
public class CorsConfig {

    @Autowired
    private AlgamoneyApiProperty algamoneyApiProperty;

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration configAutenticacao = new CorsConfiguration();
        configAutenticacao.setAllowCredentials(true);
        configAutenticacao.addAllowedOrigin(algamoneyApiProperty.getOriginPermitida());
        configAutenticacao.addAllowedHeader("Authorization");
        configAutenticacao.addAllowedHeader("Content-Type");
        configAutenticacao.addAllowedHeader("Accept");
        configAutenticacao.addAllowedMethod("POST");
        configAutenticacao.addAllowedMethod("GET");
        configAutenticacao.addAllowedMethod("DELETE");
        configAutenticacao.addAllowedMethod("PUT");
        configAutenticacao.addAllowedMethod("OPTIONS");
        configAutenticacao.setMaxAge(3600L);
        // source.registerCorsConfiguration("/oauth/token", configAutenticacao);
        source.registerCorsConfiguration("/**", configAutenticacao); // Global para todas as URLs da aplicação

        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

Solution 2:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.example.algamoney.api.config.property.AlgamoneyApiProperty;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Autowired
    private AlgamoneyApiProperty algamoneyApiProperty;

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        response.setHeader("Access-Control-Allow-Origin", algamoneyApiProperty.getOriginPermitida());
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if ("OPTIONS".equals(request.getMethod()) && algamoneyApiProperty.getOriginPermitida().equals(request.getHeader("Origin"))) {
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept");
            response.setHeader("Access-Control-Max-Age", "3600");

            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, resp);
        }

    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

}

Note: You should debug the code and verify that the call is entering the first call: "OPTIONS" .equals(request.getMethod()) , because the browser always executes an "OPTIONS" request before the call which you ordered.

    
12.03.2018 / 14:50