1

Implementei um serviço com JAX-RS que possui operações GET e POST:

@Path("/funcionario")
@Singleton
public class FuncionarioService {
    private List<Funcionario> funcionarios = new ArrayList<>();

    @GET
    @Path("/{nome}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response buscarFuncionario(@PathParam(value = "nome") String nome) {
        for (Funcionario funcionario : funcionarios) {
            if (funcionario.getNome().equals(nome))
                return Response.ok(funcionario.toJSON()).build();
        }
        return Response.status(404).build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({ MediaType.APPLICATION_JSON })
    public Response criarFuncionario(Funcionario funcionario, @Context UriInfo uriInfo) throws URISyntaxException {
        Boolean criado = criar(funcionario);
        URI location = uriInfo.getAbsolutePathBuilder().path(funcionario.getNome()).build();
        if (criado) {
            return Response.created(location).build();
        } else {
            return Response.status(HttpStatus.SEE_OTHER_303.getStatusCode()).location(location).build();
        }
    }
}

Quando eu chamo o método GET, recebo a resposta esperada de recurso não encontrado:

curl -XGET http://localhost:8080/servicorestfuljee/funcionario/giuliana --verbose
Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /funcionario/giuliana HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
> 
< HTTP/1.1 404 Not Found
< Connection: keep-alive
< X-Powered-By: Undertow/1
< Server: JBoss-EAP/7
< Content-Length: 74
< Content-Type: text/html
< Date: Fri, 05 Oct 2018 11:51:47 GMT

Para suportar a autenticação, criei um usuário chamado user com senha password através do script localizado em $JBOSS_HOME/bin/add-user.sh adicionando esse usuário no grupo user.

Depois disso, eu adicionei no arquivo web.xml a segurança para os meus serviços, fazendo assim eles solicitarem senha sempre que forem acessados:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>servicorestfuljee</web-resource-name>
        <url-pattern>/funcionario/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>PUT</http-method>
        <http-method>DELETE</http-method>
        <http-method>POST</http-method>
        <http-method>PATCH</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>user</role-name>
    </auth-constraint>
</security-constraint>

<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>ApplicationRealm</realm-name>
</login-config>

<security-role>
    <role-name>user</role-name>
</security-role>

Agora, se eu tentar acessar o serviço sem senha, vou receber o erro 401:

curl -XGET http://localhost:8080/servicorestfuljee/funcionario/giuliana --verbose
Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /servicorestfuljee/funcionario/giuliana HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
> 
< HTTP/1.1 401 Unauthorized
< Expires: 0
< Cache-Control: no-cache, no-store, must-revalidate
< X-Powered-By: Undertow/1
< Server: JBoss-EAP/7
< Pragma: no-cache
< Date: Fri, 05 Oct 2018 12:12:27 GMT
< Connection: keep-alive
< WWW-Authenticate: Basic realm="ApplicationRealm"
< Content-Type: text/html;charset=UTF-8
< Content-Length: 71

Informando o usuário e senha, eu consigo acessar o método GET:

curl -XGET http://localhost:8080/servicorestfuljee/funcionario/giuliana -u user:password --verbose
Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
* Server auth using Basic with user 'user'
> GET /servicorestfuljee/funcionario/giuliana HTTP/1.1
> Host: localhost:8080
> Authorization: Basic dXNlcjpwYXNzd29yZA==
> User-Agent: curl/7.58.0
> Accept: */*
> 
< HTTP/1.1 404 Not Found
< Expires: 0
< Cache-Control: no-cache, no-store, must-revalidate
< X-Powered-By: Undertow/1
< Server: JBoss-EAP/7
< Pragma: no-cache
< Date: Fri, 05 Oct 2018 12:16:12 GMT
< Connection: keep-alive
< Content-Type: text/html;charset=UTF-8
< Content-Length: 68

Mas se eu tentar acessar o POST, recebo erro 405:

curl --header "Content-Type: application/json" -XPOST --data '{"nome": "giuliana","idade": 20, "cargo": "arquiteta de software"}' http://localhost:8080/servicorestfuljee/funcionario --verbose -u user:password
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
* Server auth using Basic with user 'user'
> POST /servicorestfuljee/funcionario HTTP/1.1
> Host: localhost:8080
> Authorization: Basic dXNlcjpwYXNzd29yZA==
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 66
> 
* upload completely sent off: 66 out of 66 bytes
< HTTP/1.1 405 Method Not Allowed
< Expires: 0
< Cache-Control: no-cache, no-store, must-revalidate
< X-Powered-By: Undertow/1
< Server: JBoss-EAP/7
< Pragma: no-cache
< Date: Fri, 05 Oct 2018 12:16:46 GMT
< Connection: keep-alive
< Content-Type: text/html;charset=UTF-8
< Content-Length: 104

Eu procurei na documentação do JBoss EAP 7 algo que permita configurar os métodos HTTP disponíveis, mas não encontrei muita coisa. Como posso corrigir esse problema de uma forma segura?

6
  • Já tentou fazer o POST com servicosrestfuljee/funcionario/, com a barra no final? Já que no seu pattern tem a barra no final: /funcionario/*
    – Pedro
    5/10/2018 às 12:58
  • Tentei aqui, ainda dá erro 405 :/ 5/10/2018 às 13:02
  • vc quer mudar o codigo do erro? tipo de 405 para 401?
    – cpll
    5/10/2018 às 13:20
  • Eu preciso que o sistema aceite o POST, tem que retornar o objeto criado. Coloquei um breakpoint no serviço e quando eu chamo ele nem chega nele. É como se o endpoint não existisse. 5/10/2018 às 13:20
  • faz um teste, adiciona alguma coisa ao path do seu metodo, p.ex. @Path("/colaborador/{nome}")
    – cpll
    5/10/2018 às 13:24

1 Resposta 1

1

O problema ocorria porque faltava criar o responsável por expor esses endpoints no JBoss, que é o Application:

package br.gov.dataprev.servicorestfuljavaee;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("api")
public class JAXRSConfiguration extends Application {

}

Feito isso, após executar o mvn clean package, o pacote estava sendo gerado com o "-1.0" e por isso nada ficava acessível pelo path servicorestfuljee!

Com essas mudanças foi possível acessar o post pela URL correta:

curl --header "Content-Type: application/json" -XPOST --data '{"nome": "giuliana","idade": 20, "cargo": "arquiteta de software"}' http://localhost:8080/servicorestfuljee-1.0/api/funcionario --verbose -u user:password
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
* Server auth using Basic with user 'user'
> POST /servicorestfuljee-1.0/api/funcionario HTTP/1.1
> Host: localhost:8080
> Authorization: Basic dXNlcjpwYXNzd29yZA==
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 66
> 
* upload completely sent off: 66 out of 66 bytes
< HTTP/1.1 201 Created
< Expires: 0
< Cache-Control: no-cache, no-store, must-revalidate
< X-Powered-By: Undertow/1
< Server: JBoss-EAP/7
< Pragma: no-cache
< Location: http://localhost:8080/servicorestfuljee-1.0/api/funcionario/giuliana
< Date: Fri, 05 Oct 2018 13:43:46 GMT
< Connection: keep-alive
< Content-Length: 0

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

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .