1

I having troubles to post data in my Java Application, because my Angular send a http method Option.

The error retorned is:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

My API security config:

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                    .authorizeRequests()
                    .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                    .antMatchers("/api/instituicao/BuscarTodos", "/auth/**",
                            "/api/curso/BuscarEquipePorIdInstituicao/**",
                            "/api/turma/BuscarPorCursoId/**", "/api/cargo/BuscarPorInstituicaoId/**",
                            "/api/aluno/cadastrar/**", "/api/aluno/BuscarPorMatricula/**",
                            "/api/servidor/cadastrar/**", "/api/servidor/BuscarPorMatricula/**", "/api/estado/BuscarTodos/**",
                            "/api/municipio/BuscarPorIdEstado/**", "/v2/api-docs",
                            "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**")
                    .permitAll().anyRequest().authenticated();
        httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
        httpSecurity.headers().cacheControl();

My Angular app service to set headers:

let httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': 'true',
        'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type'
    })
};
/**
 * Retorna o header a ser usado na requisição e caso o usuário possua token ele é adicionado na requisição.
 * @param filter parametro a ser adicionado no cabecalho
 */
export function getHeader(filter: any = null) {
    let params: HttpParams = new HttpParams();
    if (filter != null)
        Object.keys(filter).map(k => params = params.set(k, filter[k]));
    Object.assign(httpOptions, httpOptions, { params: params });
    if (localStorage.getItem('token') != null)
        httpOptions.headers = httpOptions.headers.set('Authorization', `Bearer ${localStorage.getItem('token')}`);
    return httpOptions;

My service to post entity:

    Post<T>(route: string, obj: any) {
        return this.http.post<T>(`${environment.apiEndPoint}${route}/cadastrar`, obj, getHeader())
            .pipe(catchError(this.handleError));
    }

My controller:

    @RestController
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @RequestMapping("api/instituicao")
    public class InstitutoController extends baseController<InstituicaoDTO, Instituicao, InstituicaoService> {
        {
            mappingDTOToEntity = new Extension<>(InstituicaoDTO.class, Instituicao.class);
            mappingEntityToDTO = new Extension<>(Instituicao.class, InstituicaoDTO.class);
        }

    protected Extension<EnderecoDTO, Endereco> mappingEntityChild = new Extension<>(EnderecoDTO.class, Endereco.class);
...... @PostMapping
    public ResponseEntity<Response<InstituicaoDTO>> cadastrarInstituicao(
            @Valid @RequestBody InstituicaoDTO instituicaoDTO, BindingResult result) throws NoSuchAlgorithmException {
        log.info("Cadastrando a instituicao: {}", instituicaoDTO.toString());
        this.entityService.BuscarPorNomeInstituicao(instituicaoDTO.getNome())
                .ifPresent(inst -> result.addError(new ObjectError("instituicao", "Nome já cadastrado.")));
        if (result.hasErrors()) {
            log.error("Erro ao validar dados da nova instituicao: {}", result.getAllErrors());
            result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage()));
            return ResponseEntity.badRequest().body(response);
        }
        entity = mappingDTOToEntity.AsGenericMapping(instituicaoDTO);
        List<Endereco> listaEnderecos = entity.getEndereco();
        entity.setEndereco(new ArrayList<Endereco>());
        if (!listaEnderecos.isEmpty()) 
            listaEnderecos.forEach(endereco -> entity.AdicionarEndereco(endereco));

        entity = this.entityService.Salvar(entity);
        response.setData(mappingEntityToDTO.AsGenericMapping(entity));
        return ResponseEntity.ok(response);
}

0 Answers0