Authentication and the AbstractResource

You'll have noticed in the previous page that our classes all extend from AbstractResource. This isnt anything required by Milton but its a common pattern. The most important thing about that base class is it has the authenticate method:

   @Override
    public Object authenticate(String userName, String requestedPassword) {
        User user = contactManager.getContactsDao().findUser(userName);
        if( user != null ) {
            if( user.getPassword().equals(requestedPassword)) {
                return getRoot().child(userName); // return the webdav resource for this object
            }
        }
        return null;
    }

    @Override
    public Object authenticate(DigestResponse digestRequest) {
        User user = contactManager.getContactsDao().findUser(digestRequest.getUser());
        if (user != null) {
            DigestGenerator gen = new DigestGenerator();
            String actual = gen.generateDigest(digestRequest, user.getPassword());
            if (actual.equals(digestRequest.getResponseDigest())) {
                return getRoot().child(digestRequest.getUser()); // return the webdav resource for this object
            } else {
                log.warn("that password is incorrect. Try '" + user.getPassword() + "'");
            }
        } else {
            log.warn("user not found: " + digestRequest.getUser() + " - try 'user'");
        }
        return null;
    }

And the thing to notice about those authenticate methods is that they don't return a domain object - they return the Milton resource that represents the user.

This is critical to the success of your carddav server, and its not obvious, so watch out. The object returned must implement CardDavPrincipal and this is what permits auto-discovery of Carddav information via the .well-known protocol.