Coming Up for Air

GlassFish 3.1, REST, and a Secured Admin User

In my last post on using the GlassFish REST interface, a commenter asked about how GlassFish handles security. So far, all of my examples have been using GlassFish 3.1 out of the box, which doesn’t require authentication (as a convenience for developers, as well as system admins evaluating the server). In production, of course, the server will be secured, which means our client code will have to be modified. In this installment, we’ll see how that might be done in Java.

Let’s start with a very simple class that deploys an application to the server:

public class AuthExample {
    protected Client client;
    public AuthExample() {
        client = Client.create();

    public boolean deployApp(String fileName) throws URISyntaxException {
        FormDataMultiPart form = new FormDataMultiPart();
        form.getBodyParts().add(new FileDataBodyPart("id", new File(fileName)));
        form.field("name", fileName.substring(0, fileName.indexOf(".")),
        form.field("contextroot", fileName.substring(0, fileName.indexOf(".")),
        form.field("force", "true", MediaType.TEXT_PLAIN_TYPE);
        ClientResponse response =
                .post(ClientResponse.class, form);
        return response.getStatus() == 200;

    public static void main(String... args) {
        try {
            AuthExample example = new AuthExample();
            if (example.deployApp(args[0])) {
            } else {
        } catch (Exception e) {

If you execute this, passing a WAR as the first and only parameter, you should see "Success" printed to the screen. Now that we’ve verified this works, let’s secure the server:

$ asadmin change-admin-password
Enter admin user name [default: admin]>
Enter admin passwordthe >
Enter new admin password>
Enter new admin password again>
Command change-admin-password executed successfully.

If you rerun the class now, you should see "Failure" printed to the screen, which is what we’d expect to see. To fix this, let’s change the constructor for our test app:

public AuthExample() {
    client = Client.create();
    client.addFilter(new HTTPBasicAuthFilter("admin", "admin"));

Change the password, of course, to what you entered, and rerun the app. You should now see "Success".

Pretty simple. Ultimately, this has more to do with the Jersey Client than with GlassFish, but is still something one will need to know if using these two pieces of software together.

For the Maven people in the audience, here’s the POM I used to build this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""
    <name>Jersey plus Authentication Example</name>

I executed the project with this command line:

mvn -Prun -Dexec.args="test.war" package


tags: GlassFish REST


Sample quote

Quote source