This is the second part of the
JAX-RS Tip of the Day: Basic Authentication with JDBC. If you have not already done the pre-requisites, please examine the other article first.
Abstract
Unless you are developing a public service where authentication is not required like weather, or time services. This means that you will require authentication, and authorization. This application demonstrates how to perform basic authentication. This may be all that is required for your application, as long as, it is operating in a secure environment, or using secure transport (HTTPS).
Technical Details
If you have already completed creating a secure service, then you will really like how easy it is to create a basic authentication client for that service.
Requirements
As you can see from the code below. The most important item is to add a
HTTPBasicAuthFilter
to allow you to authenticate. Its that simple... really.
ExampleResourceClient.java
package com.bluelotussoftware.jersey;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.LoggingFilter;
/**
* REST Basic Authentication Client Application
*
* @author John Yeary
* @version 1.0
*/
public class BasicAuthenticationClient {
public static void main(String[] args) {
ExampleResourceClient erc = new ExampleResourceClient();
erc.setUsernamePassword("jyeary", "test");
System.out.println(erc.getMessage());
erc.close();
}
static class ExampleResourceClient {
private com.sun.jersey.api.client.WebResource webResource;
private com.sun.jersey.api.client.Client client;
private static final String BASE_URI = "http://localhost:8080/secure-jdbc-rest-service/resources";
public ExampleResourceClient() {
com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
client = com.sun.jersey.api.client.Client.create(config);
client.addFilter(new LoggingFilter());
webResource = client.resource(BASE_URI).path("example");
}
public String getMessage() throws com.sun.jersey.api.client.UniformInterfaceException {
WebResource resource = webResource;
return resource.accept(javax.ws.rs.core.MediaType.TEXT_PLAIN).get(String.class);
}
public void putMessage(Object requestEntity) throws com.sun.jersey.api.client.UniformInterfaceException {
webResource.type(javax.ws.rs.core.MediaType.TEXT_PLAIN).put(requestEntity);
}
public void close() {
client.destroy();
}
public void setUsernamePassword(String username, String password) {
client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(username, password));
}
}
}
3 comments :
This Blog deserves far more attention than it is getting right now
Thanks John - this just saved me an hour!
I am glad that it helped.
Post a Comment