Take me home

OpenID authentication with attributes in Play

Published October 16, 2011

In an effort to procrastinate and still get things done, I started work on a new project even though Buster.JS isn't done yet. That's more useful than spending all day playing Minecraft, I guess.

The app will support OpenID authentication. I'm using the Play framework, which has built in support for OpenID. The docs for Attribute Exchange (AX) and Simple Registration (SREG) in Play's OpenID module are very sparse, though. So I decided to write about my discoveries here.

Here's a code-dump. The routes:

GET     /login                                  Authentication.index
POST    /login                                  Authentication.create

The view:

#{form @Authentication.create()}
  <input type="text" name="openid_url" />
  <input type="submit" value="Log in" />
#{/form}

My controller:

package controllers;

import play.mvc.Controller;
import play.libs.OpenID;
import play.libs.OpenID.*;

public class Authentication extends Controller {
    public static void index() {
        if (OpenID.isAuthenticationResponse()) {
            // Postback from OpenID provider.
            UserInfo verifiedUserInfo = OpenID.getVerifiedID();

            if (verifiedUserInfo != null) {
                // Store verifiedUserInfo.id
                if (verifiedUserInfo.extensions != null) {
                    renderText(verifiedUserInfo.extensions.toString());
                } else {
                    renderText("Logged in. Failed to get attributes");
                }
            } else {
                renderText("Failed to log in.");
            }
        } else {
            // Render login form.
            render();
        }
    }

    public static void create() {
        String openIdURL = params.get("openid_url");
        OpenID openIdReq = OpenID.id(openIdURL);
            
        // Attribute Exchange (AX)
        openIdReq.required("email", "http://axschema.org/contact/email");
        openIdReq.required("firstName", "http://axschema.org/namePerson/first");
        openIdReq.required("lastName", "http://axschema.org/namePerson/last");

        // Simple Registration (SREG)
        openIdReq.required("email");
        openIdReq.optional("fullname");
        openIdReq.optional("timezone");

        // Perform redirect
        openIdReq.verify();
    }
}

The code pretty much speaks for itself. A few things to note:


Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.