Karol Wolny
Karol Wolny

Reputation: 67

CORS Spring Boot

i have problem with cors, when i call to api without header authorization i get back success data, but when i call to endpoint authorized by token, and i add header i get an error like this: Access to XMLHttpRequest at 'http://localhost:8080/merchants' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My cors filter:

package com.kompan.security.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
                                    final FilterChain filterChain) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
        response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Authorization");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addIntHeader("Access-Control-Max-Age", 10);
        filterChain.doFilter(request, response);
    }
}

Upvotes: 0

Views: 3102

Answers (4)

Bizhan Laripour
Bizhan Laripour

Reputation: 175

The simplest solution is adding @CrossOrigin("*") up to your controller

Upvotes: 0

Karol Wolny
Karol Wolny

Reputation: 67

Fix it, add bean with configuration

    @Bean
    public SecurityFilterChain securityFilterChain(final HttpSecurity http) throws Exception {
        return http
                .cors().configurationSource(request -> {
                    final CorsConfiguration cors = new CorsConfiguration();
                    cors.setAllowedOrigins(List.of("*"));
                    cors.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "HEAD", "DELETE", "OPTIONS"));
                    cors.setAllowedHeaders(List.of("Origin", "Accept", "X-Requested-With", "Content-Type", "Access-Control-Request-Method", "Access-Control-Request-Headers", "Authorization"));
                    cors.setExposedHeaders(List.of("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Authorization"));
                    return cors;
                })
                .and()
                .csrf().disable()
                .authorizeHttpRequests((requests) -> requests
                        .mvcMatchers("/swagger-ui/**").permitAll()
                        .mvcMatchers("/v3/api-docs/**").permitAll()
                        .mvcMatchers("/opinions").permitAll()
                        .mvcMatchers("/login").permitAll()
                        .mvcMatchers("/merchant_queries").permitAll()
                        .anyRequest().authenticated()
                )
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(tokenAuthorizationFilter, SecurityContextHolderAwareRequestFilter.class)
                .build();
    }

Upvotes: 0

pramod sharma
pramod sharma

Reputation: 1

@Configuration
class CorsConfiguration {
    @Bean
    fun corsConfigurer(): WebMvcConfigurer {
        return object : WebMvcConfigurer {
            override fun addCorsMappings(registry: CorsRegistry) {
                registry
                    .addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH")
            }
        }
    }
}

Upvotes: -2

WeMakeSoftware
WeMakeSoftware

Reputation: 9162

No need to implement the CORS filter by yourself.

SpringBoot has everything ready, you just need to pass the configuration.

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(mapping)
                .allowedHeaders(allowedHeaders) // *
                .exposedHeaders(exposedHeaders) // *
                .allowedMethods(allowedMethods) // *
                .allowedOrigins(allowedOrigins) // *
                .allowCredentials(allowedCredentials);  // false
    }
...
}

Upvotes: 1

Related Questions