Advertisement
tadeuespindola

CORS

May 10th, 2021
1,184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.core.Ordered;
  7. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  8. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  9. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  10. import org.springframework.web.cors.CorsConfiguration;
  11. import org.springframework.web.cors.CorsConfigurationSource;
  12. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  13. import org.springframework.web.filter.CorsFilter;
  14.  
  15. @Configuration
  16. @EnableResourceServer
  17. public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  18.    
  19.     @Override
  20.     public void configure(HttpSecurity http) throws Exception {
  21.         http.cors().configurationSource(corsConfigurationSource());
  22.     }
  23.    
  24.     @Bean
  25.     public CorsConfigurationSource corsConfigurationSource() {
  26.         CorsConfiguration corsConfig = new CorsConfiguration();
  27.         corsConfig.setAllowedOriginPatterns(Arrays.asList("*"));
  28.         corsConfig.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "DELETE", "PATCH"));
  29.         corsConfig.setAllowCredentials(true);
  30.         corsConfig.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
  31.         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  32.         source.registerCorsConfiguration("/**", corsConfig);
  33.         return source;
  34.     }
  35.  
  36.     @Bean
  37.     public FilterRegistrationBean<CorsFilter> corsFilter() {
  38.         FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(corsConfigurationSource()));
  39.         bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
  40.         return bean;
  41.     }  
  42.  
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement