Boa noite pessoal!!
Estou fazendo um API e na hora que fui integrar com Front-End Angular 11 começou a dar erro CORS:
Access to XMLHttpRequest at ‘http://localhost:8090/api/v1/produtos’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Porem consultado via Postman notei que no header está retornando de maneira diferente conforme imagem:
Onde deveria ser Origin = * veio conforme acima.
Eu implementei as seguintes classes no SpringBoot:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Autowired
private UnauthorizedHandler unauthorizedHandler;
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
AuthenticationManager authManager = authenticationManager();
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/v1/login","/api/v1/produtos").permitAll()
.antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
.permitAll()
.anyRequest().authenticated()
.and().httpBasic()
.and().csrf().disable()
.addFilter(new CorsConfig())
.addFilter(new JwtAuthenticationFilter(authManager))
.addFilter(new JwtAuthorizationFilter(authManager, userDetailsService))
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler)
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
E implementei um filtro também:
@Configuration
public class CorsConfig extends CorsFilter {
public CorsConfig() {
super(configurationSource());
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
CorsRegistration cors = registry.addMapping("/**");
cors.allowedMethods("GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS");
cors.allowedOrigins("*");
cors.allowedHeaders("*");
}
};
}
private static UrlBasedCorsConfigurationSource configurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
config.addAllowedMethod("CONNECT");
source.registerCorsConfiguration("/**", config);
return source;
}
}
Controller:
@Api(value = "API de Cadastro de produtos")
@RestController
@RequestMapping("/api/v1/produtos")
public class ProdutoController {
@Autowired
private ProdutoService service;
@GetMapping(value="/user")
public UserDTO getUser(@RequestBody UserDTO user) {
return user;
}
@ApiOperation(value = "Listar todos os produtos paginado")
@GetMapping
public ResponseEntity<Page<ProdutoDTO>> findAll(@RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size) {
Page<ProdutoDTO> produtos = service.findAll(PageRequest.of(page, size));
return ResponseEntity.ok(produtos);
}
@ApiOperation(value = "Buscar produto por id")
@GetMapping(value = "/{id}")
public ResponseEntity<ProdutoDTO> buscarPorId(@PathVariable(name = "id", required = true) Long id) {
ProdutoDTO dto = service.findById(id);
return ResponseEntity.ok(dto);
}
@ApiOperation(value = "Salvar um produto na base")
@PostMapping
@Secured({ "ROLE_ADMIN" })
public ResponseEntity<ProdutoDTO> salvar(@Valid @RequestBody ProdutoDTO produto) {
ProdutoDTO prod = service.insert(produto);
URI location = getUri(prod.getId());
return ResponseEntity.created(location).build();
}
@ApiOperation(value = "Alteração de dados do produto cadastrado")
@PutMapping(value = "/{id}")
public ResponseEntity<ProdutoDTO> update(@PathVariable(name = "id", required = true) Long id,
@Valid @RequestBody ProdutoDTO dto) {
dto.setId(id);
ProdutoDTO prod = service.update(dto, id);
return ResponseEntity.ok(prod);
}
@ApiOperation(value = "Deleta os dados do produto cadastrado")
@DeleteMapping(value = "/{id}")
public ResponseEntity<?> delete(@PathVariable("id") Long id) {
service.delete(id);
return ResponseEntity.ok().build();
}
/*
* Método para gerar URI no retorno do post
*/
private URI getUri(Long id) {
return ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri();
}
}
Desde já agradeço muito atenção.