Skip to content

Instantly share code, notes, and snippets.

@leandrogilvalle
Forked from alexandreaquiles/ClienteRest.java
Created April 14, 2016 14:10
Show Gist options
  • Save leandrogilvalle/c90acd2892526cbe24d09a9711c50756 to your computer and use it in GitHub Desktop.
Save leandrogilvalle/c90acd2892526cbe24d09a9711c50756 to your computer and use it in GitHub Desktop.
Exemplo simples de autenticação por token com JAX-RS.

Vamos fazer uma autenticação por token usando cabeçalhos HTTP.

  1. No projeto fj36-livraria, na classe ClienteRest envie um cabeçalho HTTP com o nome token e verifique se o status code do response é de erro ou não:
		Response response = cliente.target(SERVER_URI + ENTRY_POINT)
				.request()
				.header("token", "TOKEN123")
				.buildPost(Entity.json(transacao))
				.invoke();
		if (response.getStatus() != Status.UNAUTHORIZED.getStatusCode()) {
			Pagamento resposta = response.readEntity(Pagamento.class);
			//autenticado...
		}
		//erro na autenticação...
  1. No projeto fj36-webservice, faça a verificação do valor token na classe PagamentoResource e lance uma exceção se necessário:
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response criaPagamento(Transacao transacao, @HeaderParam("token") String token) throws URISyntaxException {
		if(!"TOKEN123".equals(token)){
			throw new NotAuthorizedException("Token inválido.");
		}
    //...		
	}
package br.com.caelum.livraria.rest;
import java.io.Serializable;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import br.com.caelum.livraria.modelo.Link;
import br.com.caelum.livraria.modelo.Pagamento;
import br.com.caelum.livraria.modelo.Transacao;
@Component
@Scope("request")
public class ClienteRest implements Serializable {
private static final long serialVersionUID = 1L;
private static final String SERVER_URI = "http://localhost:8080/fj36-webservice";
private static final String ENTRY_POINT = "/pagamentos/";
public Pagamento criarPagamento(Transacao transacao) {
Client cliente = ClientBuilder.newClient();
Response response = cliente.target(SERVER_URI + ENTRY_POINT)
.request()
.header("token", "TOKEN123")
.buildPost(Entity.json(transacao))
.invoke();
if (response.getStatus() != Status.UNAUTHORIZED.getStatusCode()) {
Pagamento resposta = response.readEntity(Pagamento.class);
System.out.println("Pagamento criado, id: " + resposta.getId());
return resposta;
}
return null;
}
public Pagamento confirmarPagamento(Pagamento pagamento) {
Link linkConfirmar = pagamento.getLinkPeloRel("confirmar");
Client cliente = ClientBuilder.newClient();
Pagamento resposta = cliente.target(SERVER_URI + linkConfirmar.getUri())
.request()
.build(linkConfirmar.getMethod())
.invoke(Pagamento.class);
System.out.println("Pagamento confirmado, id: " + resposta.getId());
return resposta;
}
}
package br.com.caelum.payfast.rest;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import br.com.caelum.payfast.modelo.Pagamento;
import br.com.caelum.payfast.modelo.Transacao;
@Path("/pagamentos")
@Singleton
public class PagamentoResource {
private Map<Integer, Pagamento> repositorio = new HashMap<>();
private Integer idPagamento = 1;
public PagamentoResource() {
Pagamento pagamento = new Pagamento();
pagamento.setId(idPagamento++);
pagamento.setValor(BigDecimal.TEN);
pagamento.comStatusCriado();
repositorio.put(pagamento.getId(), pagamento);
}
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Collection<Pagamento> todos() {
return repositorio.values();
}
@GET
@Path("/{id}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Pagamento buscaPagamento(@PathParam("id") Integer id) {
return repositorio.get(id);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response criaPagamento(Transacao transacao, @HeaderParam("token") String token) throws URISyntaxException {
if(!"TOKEN123".equals(token)){
throw new NotAuthorizedException("Token inválido.");
}
Pagamento pagamento = new Pagamento();
pagamento.setId(idPagamento++);
pagamento.setValor(transacao.getValor());
repositorio.put(pagamento.getId(), pagamento);
pagamento.comStatusCriado();
System.out.println("PAGAMENTO CRIADO: " + pagamento);
return Response.created(new URI("/pagamentos/"+pagamento.getId())).type(MediaType.APPLICATION_JSON).entity(pagamento).build();
}
@PUT
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Pagamento confirmaPagamento(@PathParam("id") Integer id) {
Pagamento pagamento = repositorio.get(id);
pagamento.comStatusConfirmado();
System.out.println("PAGAMENTO CONFIRMADO: " + pagamento);
return pagamento;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment