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?
servicosrestfuljee/funcionario/
, com a barra no final? Já que no seu pattern tem a barra no final:/funcionario/*