You probably don't want everybody in the world to connect to your service and access (and update!) arbitrary data. The first step in securing Cayenne service is implementing client authentication. The easiest way to do it is to delegate the authentication task to the web container that is running the service. HessianConnection used in the previous chapter supports such authentication on the client side.
First we need to setup support for BASIC authentication in Jetty.
- In cayenne-tutorial project folder create a file called "jetty-realm.properties" with the following line of text:
This file will store our user database. In each line the first word is a user name, the second - password, the rest are the roles of this user. So we've created a single user with login id "cayenne-user", password "secret" and "cayenne-service-user" role.
- In the same folder create another file called "jetty-run-config.xml" with the following contents:
This file is a Jetty-specific descriptor that emulates your existing JettyLauncher setup with one extra twist - an authentication realm.
- In Eclipse go to "Run > Run..." and select "cayenne-tutorial" Jetty configuration.
- Select a "Use a Jetty XML Configuration File" radio button and navigate to "jetty-run-config.xml" file that we just created:
- Click "Apply" and close the dialog.
As you may have guessed the procedure above is Jetty-specific and will be different on other servers (such as Tomcat) or with other authentication mechanisms (such as database realms).
- open web.xml and add security constraints for the web service, just like you would do in a normal web application. The following XML has to be added just before the closing "web-app" tag:
- Save the file, shut down and restart the server and try to run the client. This time you should get an exception similar to this one:
- Go to the client Main class, and change the line that creates ClientConnection to take user name and password:
Now if you start the client again, it should successfully connect to the server and print the output similar to what we've seen before. Of course in a real application you might want secure the autentication with SSL. The technique above still applies, but you'll need to do some setup on the server. Consult your server documentation on how to enable HTTPS. On the client you would simply replace "http://" with "https://" in the server URL.
You are done with the tutorial!