Home > Articles > Programming

Managing User Accounts with Mozilla Persona (BrowserID)

  • Print
  • + Share This
Mozilla Persona gives users a way to assert their identity with implementing websites and mobile web applications. As opposed to other services that can give app developers large amounts of user information, Persona, by design, only reveals the user's email address. Any information the developer compiles on the user is siloed with that developer, there's no central database with which to share it. If they choose, users can use a different persona for every website. In this article, Developer James Williams discusses Mozilla Persona and shows you how to enable it on a simple blog site.

Read Learning HTML5 Game Programming: Build Online Games with Canvas, SVG, and WebGL and more than 24,000 other books and videos on Safari Books Online. Start a free trial today.



From the author of

Several of the Silicon Valley titans have been working to get users to use their service as an identity service for new accounts. Facebook, with its estimated 1 billion users, has set the standard in this area with dozens of new startups launching every day requiring a Facebook account, attached to one's real name, to create an account. Twitter and the newly launched Google+ Sign-In are other important players in the space.

Mozilla Persona takes a different strategy from Facebook, Twitter, and Google in embracing a decentralized model. That's to say that no one website will have access to all your information. A user is only identified by his verified email address. Email accounts can be created and destroyed much more easily than social media accounts, allowing users to better manage privacy.

In this article, you learn how to allow users to manage and create accounts using an email address on third-party websites.

Getting Started

The first thing we need to do to enable support is to include the following tag on the pages that will be doing login and logout. The listed file acts as a polyfill and adds an id attribute to the navigator object that is present in all browsers.

<script src="https://login.persona.org/include.js"></script>

The functions attached to that id attribute will facilitate login and logout as well as the mechanism to surface a popup to authenticate with Mozilla Persona. They are navigator.id.request, navigator.id.logout, and navigator.id.watch. As shown in the JavaScript snippet below, request starts the flow for the user to log in to the website. Likewise, logout revokes the current session for the user and takes them to a logged-out state.

var signinLink = document.getElementById('signin');
if (signinLink) {
  signinLink.onclick = function() { navigator.id.request(); };
}
var signoutLink = document.getElementById('signout');
if (signoutLink) {
  signoutLink.onclick = function() { navigator.id.logout(); };
}

Executed alone, request and logout do very little by themselves. navigator.id.watch does the real heavy lifting. When the user logs in to Persona, the user is first asked in a Persona pop-up if he or she wants to sign in to the listed site. Provided that login was successful, the pop-up passes a token, an assertion in Mozilla's parlance, to the calling web page asserting that the user is who that person claims to be. Below is an instance of the watch function monitoring for change in state.

var currentUser = null;
navigator.id.watch({
  loggedInUser: currentUser,
  onlogin: function(assertion) {
    if (sessionStorage['currentUser'] != undefined) {
      return;
    }
    $.ajax({
      type: 'POST',
      url: '/login', // This is a URL on your website.
      data: {assertion: assertion},
      success: function(res, status, xhr) {
        sessionStorage['currentUser'] = res;
        window.location.reload();
      },
      error: function(xhr, status, err) {
        navigator.id.logout();
        alert("Login failure: " + err);
      }
    });
  },
  onlogout: function() {
    $.ajax({
      type: 'POST',
      url: '/logout', // This is a URL on your website.
      success: function(res, status, xhr) {
        sessionStorage.removeItem('currentUser');
        window.location.reload();
      },
      error: function(xhr, status, err) { alert("Logout failure: " + err); }
    });
  }
});
Wiring Up the Server

Wiring Up the Server

We are not quite done yet. Even though you received an assertion, you can't just trust it blindly as it could be the result of a man in the middle attack. At this point, all we know is that we have something that resembles an assertion but have no idea if it is valid or not. To verify it (or even to log out), we need to issue an AJAX call to the backend, as shown above. The backend server makes a call to a verification service locally or using Mozilla's hosted solution, passing the assertion and the audience (the referring website). You will receive either a JSON object with the verified email, website, expiration time, and issuer of the assertion, if successful, or one containing a reason for failure. Below is the server-side Groovy (Java) code for handling assertions. It's not really doing anything special and can be done by any server side library capable of making HTTP POST requests.

if (params.assertion == null)
  response.setStatus(400)
def httpPost = new HttpPost("https://verifier.login.persona.org/verify")
def nvps = new ArrayList<NameValuePair>()
nvps.add new BasicNameValuePair("assertion", params.assertion)
nvps.add new BasicNameValuePair("audience", "http://0.0.0.0:5000/")
httpPost.setEntity(new UrlEncodedFormEntity(nvps))
def postResponse = httpclient.execute(httpPost)
// get response
try {
  if (postResponse.getStatusLine().getStatusCode() == 200) {
      def entity2 = postResponse.getEntity()
      def verificationData = new JSONObject(entity2.getContent().getText())
      println verificationData
      // Check if assertion was valid
      if (verificationData.status.equals('okay')) {
        def session = request.getSession(true)
        // set email and session data in Java session
        session.setAttribute('email', verificationData.email)
        session.setAttribute('data', verificationData)
        return verificationData.email
      }
      EntityUtils.consume(entity2)
  }
} finally {
  httpPost.releaseConnection()
}

Validating the assertion is the point where you should also add the assertion to your session object, be that just on the server in an HttpSession object or on the client with sessionStorage. For the small blog example I completed, you must be validated to create a post; however, in its current state, anyone who has a Mozilla account can create a post. If I were planning to run this as a personal blog or for a limited number of friends, instead of allowing the person to log in if the assertion checked out, I could check the valid assertion's email against a white list of permitted users. Beyond just login and logout, this could be an interesting means to run signups for a beta app—quick, easy, and painless for both parties. The user didn't spend 10-20 minutes filling out a long form only to learn they are 50,000th in line and the website owner has a powerful means to contact the user when he or she has been approved.

Supported Browsers

Supported Browsers

Persona is supported on all of the major desktop browsers: Chrome, Firefox, Safari, and recent versions of Internet Explorer. Internet Explorer Compatibility Mode has some quirks that need to be taken into account, but generally any browser that supports window.postMessage and localStorage should work. You can find a more detailed list of supported browsers, including mobile browsers, on the Mozilla Developer Network website.

Plugins and Extensions

Plugins and Extensions

If your existing architecture uses a web framework that doesn't make it as easy to make arbitrary web requests, check out the list of libraries and plugins to see if your framework already has a plugin or extension. In general, JavaScript (Node), PHP, Python, and Ruby have good coverage with a smattering of libraries for Java, C#, and Go.

Conclusion

Conclusion

In this article, we quickly wired up a small website to use Mozilla Persona for authentication. We also discussed the environments in which Persona would function and specific strategies for protecting our users and ourselves. Mozilla Persona offers a simple and non-obtrusive means to allow your users to log in. Download the source code for the sample project, and read more about Mozilla Persona.

  • + Share This
  • 🔖 Save To Your Account