Skip to content

Instantly share code, notes, and snippets.

@sommereder
Created February 11, 2021 07:01
Show Gist options
  • Select an option

  • Save sommereder/d81c754a46a0d79f54a175e9ccbca738 to your computer and use it in GitHub Desktop.

Select an option

Save sommereder/d81c754a46a0d79f54a175e9ccbca738 to your computer and use it in GitHub Desktop.

Revisions

  1. sommereder created this gist Feb 11, 2021.
    42 changes: 42 additions & 0 deletions WebConfiguration.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    package com.acme.tree.config;

    import java.util.Arrays;
    import java.util.Collections;

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

    import com.amce.tree.rest.ApiErrorAttributes;

    /**
    * Configuration for CORS handling and injecting our custom error attributes.
    */
    @Configuration
    public class WebConfiguration {

    @Autowired
    private AcmeConfiguration acmeConfiguration;

    @Bean
    public ErrorAttributes errorAttributes() {
    return new ApiErrorAttributes(acmeConfiguration.getApiVersion());
    }

    @Bean
    public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
    }

    }