Problem with the Cors Spring Boot and Angular 4

1

I am using a Api Rest with Spring boot with a basic auth of spring security, When I make the request to the backend with Angular it gives me as a result a problem with the Cors 'login:

  

1 Failed to load link : Request header field Cache-Control is not allowed by Access-Control-Allow-Headers in preflight response. '

I leave you how are the configurations.

  • Structure:
  • WebSecurityConfig code (basic auth of spring security)

    @EnableWebSecurity
    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
            http.authorizeRequests().antMatchers("/").permitAll().anyRequest().fullyAuthenticated().and().httpBasic().and()
                    .csrf().disable();
        }
    }
    
  • Code of the CorsFiltes.

    @Component
    @Configuration
    public class CorsFilter implements Filter {
    
        private final Logger log = LoggerFactory.getLogger(CorsFilter.class);
    
        public CorsFilter() {
            log.info("SimpleCORSFilter init");
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {
    
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
    
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers",
                    "Content-Type, Accept, X-Requested-With, remember-me, authorization, x-auth-token");
    
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                chain.doFilter(req, res);
            }
        }
    
        @Override
        public void init(FilterConfig filterConfig) {
        }
    
        @Override
        public void destroy() {
        }
    
    }
    
  • Configuring the headers in angular (Login Service)

    @Injectable()
    export class LoginService {
    
        private url = environment.REST_API_URL;
        private headers;
        private options;
    
        constructor(public http: Http) {
            this.headers = new Headers({
                'Content-Type': 'application/json',
                'Cache-Control': 'no-cache',
                'Authorization': 'Basic dXNlcjpwcm9fR2FjZTIwMTg=',
            })
    
        }
    
        loguearAlumno(personaLoguear) {
            //Peticion al backend
            return this.http.post(this.url + 'alumno/loginAlumno', JSON.stringify(personaLoguear),
                { headers: this.headers }).map(res => res.json());
    
        }
    }
    
  • asked by Álvaro Sánchez 22.04.2018 в 16:19
    source

    3 answers

    0

    The server to which the POST request is sent must include the header Access-Control-Allow-Headers

    This is because it is up to the server to specify that it accepts cross-origin requests and allows the content type request header, etc. The client can not decide for himself that a given server must allow CORS.

    An example can be like this:

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", 
    "my-authorized-proxy-or-domain");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", 
    "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
        chain.doFilter(req, res);
    }
    
        
    answered by 24.04.2018 / 17:20
    source
    0

    That same problem I solved putting the tag

      

    @Cors

    about the classes that published the API from Spring boot.

        
    answered by 24.04.2018 в 12:07
    0

    The error tells you that in the sentence:

    response.setHeader("Access-Control-Allow-Headers",
                "Content-Type, Accept, X-Requested-With, remember-me, authorization, x-auth-token");
    

    The header Cache-Control is not.

    On the other hand, and as a more general and permanent solution: Have you thought about using the reverse proxy option of the angle server? It will avoid all CORS problems.

        
    answered by 24.04.2018 в 17:33