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 aHTTPBasicAuthFilter
to allow you to authenticate. Its that simple... really.
ExampleResourceClient.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 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; 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)); } } } |