Şu satırı dahil ederiz.
Örnekimport org.springframework.web.filter.CorsFilter;
constructor - CorsConfiguration
HttpSecurity.cors() metodu ile eklenen Spring filtresi kod şuna benzer. Yani aslında bir CorsFilter nesnesi ekliyor.
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
doFilter metodu
Örnek
Eğer bu kodu kendimiz ekleseydik şöyle olurdu. Burada kendi kodumuz CorsFilter'dan kalıtmıyor.@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCorsFilterConfig implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type,
enctype");
response.setHeader("Access-Control-Max-Age", "3600");
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req)
.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
Kendi kodumuzu ekleseydik şöyle olurdu. Burada kendi kodumuz CorsFilter'dan kalıtmıyor.
@Componentpublic class CustomCorsFilter extends OncePerRequestFilter {@AutowiredOriginService originService;CorsProcessor processor = new DefaultCorsProcessor();@Overrideprotected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {CorsConfiguration config = new CorsConfiguration();config.setAllowCredentials(true);List<String> origins = originService.getOrigins();config.setAllowedOrigins(origins);config.setAllowedMethods(List.of("OPTIONS", "HEAD", "GET", "POST"));config.addAllowedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);CorsConfiguration corsConfiguration = source.getCorsConfiguration(request);boolean isValid = this.processor.processRequest(corsConfiguration, request, response);if (!isValid || CorsUtils.isPreFlightRequest(request)) {return;}filterChain.doFilter(request, response);}}
Hiç yorum yok:
Yorum Gönder