Search code examples
angularspring-bootspring-boot-security

Getting Cors Error when making api calls in angular


I have written my backend in spring boot and running on (localhost:9090) and the frontend is running on angular (localhost:4200).

I am facing this issue when trying to get data from the backend.

Access to XMLHttpRequest at 'http://localhost:9090/vendor-data/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

This is the Service file -

  getVendorData(headersData:any):Observable<any>{
    return this.http.get('http://localhost:9090/vendor-data/',{headers:headersData});
  }

This is the component.ts file -

ngOnInit() {
    const token = localStorage.getItem('token');
    const headers = new HttpHeaders({
      Authorization: `Bearer ${token}`,
    });
    console.log(this.data.getVendorData(headers))
    this.data.getVendorData(headers).subscribe({
      next: (v) => {
        this.vendorList = v;
      },
      error: (e) => {},
      complete: () => { },
    });
  }

This is the config file in the backend -

@Configuration
@EnableWebMvc
public class VendorConfiguration implements WebMvcConfigurer {

    public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/**").allowedOrigins("http://localhost:4200")
         .allowedMethods("GET", "POST", "PUT", "DELETE")
             .allowCredentials(true);                                                                               
    }
}

I also tried using @CrossOrigin("*") in the Controller file but I am still getting the same issue.

public class DataFilter extends OncePerRequestFilter{
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        String token=extractToken(request);
        boolean isError=true;
        
        if(token!=null && token.length()>6) {
            try {
                Jwts
                .parserBuilder()
                .setSigningKey(Keys.hmacShaKeyFor(Decoders.BASE64URL.decode(
                        "f9b2b91e3c468f1937598573b00d923426127dc06bf6cc8b446fac9ec1364f88")))
                .build()
                .parseClaimsJws(token)
                .getBody();
                isError=false;
                filterChain.doFilter(request, response);
            }
            catch(SignatureException e) {
                System.out.print("Invalid Signature");
            }
            catch(MalformedJwtException e) {
                System.out.print("Invalid Token");
            }
        }
        if(isError) {
            (response).sendError(HttpStatus.UNAUTHORIZED.value(),"Unauthorized");
        }
    }

    private String extractToken(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String token = null;
        if (authHeader != null) {
            token = authHeader.substring(7);
        }
        return token;
    }

Is this filter class causing the errors?


Solution

  • Just added this to the api-gateway

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.addAllowedOrigin("*");
        corsConfig.addAllowedMethod("*");
        corsConfig.addAllowedHeader("*");
        corsConfig.setAllowCredentials(true);
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);
    
        return new CorsWebFilter(source);
    }
    

    and it removed the cors error