-1

I have deployed Angular project in it's own app service and also deployed Spring Boot project in its own app service. The two applications work fine locally but the problem comes on production. I get this error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mineralsportal-api.azurewebsites.us/auth_api/authenticate. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 503

I don't know where the error comes from since I configured the cross-origin class to enable resource sharing and corsFilter class in Spring Boot but I'm getting this error on Azure (production) even though it works perfectly fine locally.

Here is my CorsConfig class:

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE")
                    .allowedOrigins("*")
                    .allowedHeaders("*");
            }
        };
    }
}

Here is my CorsFilter class:

@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        chain.doFilter(req, res);
    }
    
    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}

Here is my SecurityConfig class:

@Configuration
@EnableWebSecurity
@SuppressWarnings("deprecation")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserService userService;

    @Autowired
    private RequestFilter requestFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable();
        http.csrf().disable();
        http
            .authorizeRequests()
                .antMatchers("/auth_api/authenticate").permitAll()
                .anyRequest().authenticated()
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http
            .addFilterBefore(requestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

After a lot of googling I was not able to get the best answer that could help me resolve the issue any suggestions will be much I appreciated.

Are there any means in Azure I can deploy both applications to run on the same app service (Angular + Spring Boot) without packaging them on the same JAR file?

dur
  • 15,689
  • 25
  • 79
  • 125
  • Why are you disabling CORS with `http.cors().disable();`, if you want to use CORS. That makes not sense. You have to enable it. – dur May 21 '23 at 09:12

1 Answers1

0

Maybe https://howtodoinjava.com/spring-boot2/spring-cors-configuration/ can help you. In the fourth paragraph you can find an example on how to configure CorsConfigurationSource and set AllowedOrigins

try also

@Override
    protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/auth_api/authenticate").permitAll().anyRequest().authenticated()
    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(requestFilter, UsernamePasswordAuthenticationFilter.class);
    http.cors().configurationSource(request -> new CorsConfiguration(corsConfiguration()));
}

@Bean
    CorsConfiguration corsConfiguration() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setAllowedOrigins(Arrays.asList(//your link here));
        corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control, Allow-Origin", "Content-Type",
                "Accept", "Authorization", "Origin, Accept", "X-Requested-With", "Access-Control-Request-Method",
                "Access-Control-Request-Header"));
        corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
                "Access-Control-Request-Allow-Origin", "Access-Control-Allow-Credentials"));
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        return corsConfiguration;
    }
dannyRouge
  • 61
  • 5
  • 1
    Thanks for that @dannyRounge I can see now the /auth_api/authenticate works but af successfully login the system goes to dashboard but other API's or end points that require headers for them to provide data are blocked any idea on that – Janeth Jackson May 18 '23 at 13:13
  • are you using interceptor in your angular app? https://angular.io/api/common/http/HttpInterceptor Interceptor allow you to clone request and add your custom header like authorization token and more – dannyRouge May 18 '23 at 13:16
  • yes it is present inside my angular application and it works fine locally the only problem it comes when the application goes to live I can't figure it out what is going on. – Janeth Jackson May 18 '23 at 13:26
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/253721/discussion-between-janeth-jackson-and-dannyrouge). – Janeth Jackson May 18 '23 at 14:30