0

Estou tentando fazer uma resquest do tipo post com credentials (token) para minha api construída com spring boot.
Mas estou tendo problemas para especificar a origem que eu passo como parâmetro para o método CorsRegistry.allowOrigins().
As duas origens que tentei foram : "http://localhost/*" e "https://italomp.github.io/interface-CRUD/".

A segunda origem é de uma interface que hospedei no github.io. Mas ao fazer a requisição, vejo no console do browser que ocorreu um erro de preflighted request.
Este erro não deveria acontecer, pois configurei as origens, os cabeçalhos e o métodos que o servidor aceita e são esses os elementos que a preflighted request analisa.

Então pergunto:

  1. Como especificar a origem "localhost" em CorsRegistry.allowOrigins()?
  2. Por que não dá certo quando eu uso a origem do github.io/?

CÓDIGO JAVA - Classe com a anotação @SpringBootApplication:

package com.crud.rest;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;

/**
 * This is the main class of the project, because it has 
 * springBootApplication annotation. That's why it
 * is the responsible class for uploading the spring server.
 */
@SpringBootApplication
@ComponentScan("com.crud")
public class CrudApplication {

    /**
     * This static method start the spring server.
     * @param args: argument array.
     */
    public static void main(String[] args) {
        SpringApplication.run(CrudApplication.class, args);
    }
    
    /**
     * This method is responsible for filtering tokens for 
     * private routes. And here are noted all the private routes.
     * The '*' at the end of the route indicates that all the routes
     * beginning with "/v1/product/private/" are being passed as a 
     * parameter to the addUrlPatterns method.
     */
    @Bean
    public FilterRegistrationBean filterJwt(){
        FilterRegistrationBean filter = new FilterRegistrationBean();
        filter.setFilter(new TokenFilter());
        filter.addUrlPatterns("/v1/product/private/*");
        return filter;
    }

    @Configuration
    public class MyConfiguration {

        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return (WebMvcConfigurer) new WebMvcConfigurerIplmts() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                            .allowedOrigins("http://localhost/*") //this value can't be "*", because allowCredentials(true).
                            .allowedMethods("PUT", "DELETE","POST","GET")
                            .allowedHeaders("Content-type", "Authorization")
                            .allowCredentials(true)
                            .maxAge(3600);
                }
            };
        }
        
        public class WebMvcConfigurerIplmts implements WebMvcConfigurer{
            
            public WebMvcConfigurerIplmts() {
                
            }
        }
    }

CÓDIGO JAVA - Classe TokenFilter:

package com.crud.rest;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.filter.GenericFilterBean;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;

/** 
 * This class is responsible for filtering the received tokens
 * in the requests.
 * @author Italo Modesto
 */
public class TokenFilter extends GenericFilterBean{

    /**
     * This method applies a filter on tokens to verify if it's valid.
     * 
     * Firstly, this method converts ServeletRequest to HttpServlerReques 
     * to be able to access its authorization attribute;
     * 
     * then this method extracts the authorization attribute from 
     * the request and check if the attribute is null or badly formatted (in
     * these cases, exceptions will be throws);
     * 
     * Finally, The token is extracted from the request and unpacked for it
     * can be passed as parameter to the filter chain.
     * 
     * The filter chain (in this case) call the resource requested.
     * 
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String auth = req.getHeader("Authorization");                 
        if(auth == null || !auth.startsWith("Bearer ")) {
            throw new ServletException("Token inexistente ou mal formatado");
        }
        String token = auth.substring(7);
        try {
            Jwts.parser().setSigningKey("caneca").parseClaimsJws(token).getBody();
        }catch(SignatureException e) {
            throw new ServletException("Token inválido ou expirado");
        }
        chain.doFilter(request, response);
    }

}

ERROS QUE O CONSOLE DO BROWSER MOSTRA:

Access to fetch at 'http://localhost:8080/api/v1/user/' from origin 'null' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
script.js:43 

POST http://localhost:8080/api/v1/user/ net::ERR_FAILED
(anonymous) @ script.js:43
index.html:1 

Uncaught (in promise) TypeError: Failed to fetch

CÓDIGO JAVASCRIPT DO FRONT

let buttonUserRegistry = document.getElementById("buttonUserRegistry");
let buttonUserLogin = document.getElementById("buttonUserLogin");
let buttonCreateProduct = document.getElementById("buttonCreateProduct");
let buttonReadProduct = document.getElementById("buttonReadProduct");
let buttonUpdateProduct = document.getElementById("buttonUpdateProduct");
let buttonDeleteProduct = document.getElementById("buttonDeleteProduct");
let result = document.getElementById("result");

/**
 * Esse trecho de código adiciona um evento ao elemento
 * buttonUserRegistry.
 * 
 * evento: click
 * 
 * callback: função que coleta dados do novo usuario no form com 
 * id "userRegistry" e envia esses dados para p servidor através 
 * de uma requisição POT.
 * Esses daados compõe um novo usuário que será cadastrado no 
 * servidor
 */
buttonUserRegistry.addEventListener("click", function(){
    let form = document.getElementById("userRegistry");
    let inputName, inputLogin, inputPassword;
    let newUser, registerUrl, optRequest;
    for(e of form){
        if(e.name == "inputName"){
            inputName = e.value;
        }
        else if(e.name == "inputLogin"){
            inputLogin = e.value;
        }
        else if(e.name == "inputPassword"){
            inputPassword = e.value;
        }
    }
    newUser = {"name": inputName, 
               "login": inputLogin, 
               "password": inputPassword};
    registerUrl = "http://localhost:8080/api/v1/user/";
    optRequest = {method: "post",
                  headers: {"Content-type": "application/json"},
                  body: JSON.stringify(newUser)};
    fetch(registerUrl,optRequest)
    .then(resp => result.innerText = resp.status);
});

/**
 * Esse trecho de código adiciona um evento ao elemento 
 * "buttonUserLogin".
 * 
 * evento: click
 * 
 * callback: função que coleta dados do usuário que vai
 * efetuar login (esses dados estão no form que usa o
 * id "userLogin") e envia uma requisição POST para o
 * servidor.
 * E ainda, armaena o token recebido do servido no
 * localStorage.
 */
buttonUserLogin.addEventListener("click", function(){
    let form = document.getElementById("userLogin");
    let inputLogin, inputPassword;
    let user, loginUrl, optRequest;
    for(e of form){
        if(e.name == "inputLogin"){
            inputLogin = e.value;
        }
        else if(e.name == "inputPassword"){
            inputPassword = e.value;
        }
    }
    user = {"login": inputLogin, 
            "password": inputPassword};
    loginUrl = "http://localhost:8080/api/v1/auth/login";
    optRequest = {method: "post",
                  headers: {"Content-type": "application/json"},
                  body: JSON.stringify(user)};
    fetch(loginUrl, optRequest)
    .then(resp => resp.json())
    .then(tokenObject => window.localStorage.setItem("token", tokenObject.token))
    .then(result.innerText = "Login realizado com sucesso!");
});

buttonCreateProduct.addEventListener("click", function(){
    let form = document.getElementById("createProduct");
    let inputName, inputDescription, inputPrice;
    let newProduct, createProductUrl, optRequest, token;
    for(e of form){
        if(e.name == "inputName"){
            inputName = e.value;
        }
        else if(e.name == "inputDescription"){
            inputDescription = e.value;
        }
        else if(e.name == "inputPrice"){
            inputPrice = e.value;
        }
    }
    newProduct = {"name": inputName, 
                  "description": inputDescription, 
                  "price": inputPrice};
    createProductUrl = "http://localhost:8080/api/v1/product/private/";
    token = window.localStorage.getItem("token");
    optRequest = {method: "post",
                  headers: {"Content-type":"application/json",
                            "Authorization":"Bearer " + token},
                  credentials: "include",
                  body: JSON.stringify(newProduct)};
    fetch(createProductUrl, optRequest)
    .then(resp => {result.innerText = resp.status;});
    console.log(token);
});


/*
let inputName;
let inputLogin;
let inputPassword;
let inputDescription;
let inputPrice;
let inputProductID;
function inputCollector(){

}
for(e of form){
    if(e.name == "inputName"){
        inputName = e.value;
    }
    else if(e.name == "inputLogin"){
        inputLogin = e.value;
    }
    else if(e.name == "inputPassword"){
        inputPassword = e.value;
    }
    else if(e.name == "inputDescription"){
        inputDescription = e.value;
    }
    else if(e.name == "inputPrice"){
        inputPrice = e.value;
    }
    else if(e.name == "inputProductID"){
        inputProductID = e.value;
    }
}
*/`

5
  • chutando aqui, mas acredito que você precise especificar a porta, se você deixar .allowedOrigins("localhost*") , eu acredito que ele vá considerar a porta 80 25/09/2020 às 12:32
  • Para a origem "italomp.github.io/interface-CRUD" eu fiz uma tentativa especificando a porta (italomp.github.io/interface-CRUD/:80), mas não funcionou. Para a origem localhost eu não sei que porta devo especificar, pois acho que a minha aplicação local vai rodar em portas diferentes cada fez que eu executar a aplicação... 26/09/2020 às 14:14
  • o certo seria italomp.github.io:80/interface-CRUD, mas como eu disse anteriormente, quando não se coloca nada ele já pressupõe que a porta é 80, no seu caso local o que eu imagino localhost:8080, já que é o que seu front está chamando, outra coisa que notei é que você esta tentando mandar um token de autorização mas não vi no seu back onde isso está sendo tratado, enfim, está nebuloso, acho que precisa dar mais detalhes 26/09/2020 às 23:02
  • Editei a minha pergunta e adicionei a classe responsável por verificar a validade do token, Lucas. Mas eu consigo fazer essa requisição usando o programa Postman, então acredito que não haja problema no tratamento do token, mas sim no CORS mesmo. Esse é o link do repositório no qual o código (API) está hospedado: github.com/italomp/API-RESTful-using-spring-boot 28/09/2020 às 1:23
  • abri seu projeto aqui e testei usando a api do github.io,, no allowedOrigins deixei apenas "italomp.github.io" e funcionou normalmente, acredito que localmente se você colocar "localhost:8080" também irá funcionar 28/09/2020 às 12:15

0

Você deve fazer log-in para responder a esta pergunta.

Pesquise outras perguntas com a tag .