• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Archive of obsolete content
  1. MDN
  2. Archive of obsolete content
  3. Archived Mozilla and build documentation
  4. Persona
  5. Quick Setup

Quick Setup

In This Article
  1. Step 1: Include the Persona library
    1. Suppressing Compatibility Mode
  2. Step 2: Add login and logout buttons
  3. Step 3: Watch for login and logout actions
  4. Step 4: Verify the user’s credentials
  5. Step 5: Review best practices

On November 30th, 2016, Mozilla shut down the persona.org services. Persona.org and related domains will soon be taken offline.

For more information, see this guide to migrating your site away from Persona:

https://wiki.mozilla.org/Identity/Persona_Shutdown_Guidelines_for_Reliers

Adding the Persona login system to your site takes just five steps:

  1. Include the Persona JavaScript library on your pages.
  2. Add “login” and “logout” buttons.
  3. Watch for login and logout actions.
  4. Verify the user’s credentials.
  5. Review best practices.

You should be able to get up and running in a single afternoon, but first things first: If you’re going to use Persona on your site, please take a moment and subscribe to the Persona notices mailing list. It’s extremely low traffic, only being used to announce changes or security issues which might adversely impact your site.

Step 1: Include the Persona library

Persona is designed to be browser-neutral and works well on all major desktop and mobile browsers.

In the future, we expect browsers to provide native support for Persona, but in the meantime, we provide a JavaScript library that fully implements the user interface and client-side part of the protocol. By including this library, your users will be able to sign in with Persona whether or not their browser has native support.

Once this library is loaded in your page, the Persona functions you need (watch(), request(), and logout()) will be available in the global navigator.id object.

To include the Persona JavaScript library, place this script tag at the bottom of the page body:

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

You must include this on every page which uses navigator.id functions. Because Persona is still in development, you should not self-host the include.js file.

Suppressing Compatibility Mode

You should also make sure users of Internet Explorer can't use Compatibility Mode, as this will break Persona. To do this:

  • either include <meta http-equiv="X-UA-Compatible" content="IE=Edge"> on your page, before any script elements
  • or set the following HTTP header on your page: X-UA-Compatible: IE=Edge.

For more information, see the notes in IE Compatibility Mode and "IE8 and IE9 Complications".

Step 2: Add login and logout buttons

Because Persona is designed as a DOM API, you must call functions when a user clicks a login or logout button on your site. To open the Persona dialog and prompt the user to log in, you should invoke navigator.id.request(). For logout, invoke navigator.id.logout(). Note, the call to logout() must be made in the click handler of the logout button.

For example:

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(); };
}

What should those buttons look like? Check out our Branding Resources page for premade images and CSS-based buttons!

Step 3: Watch for login and logout actions

For Persona to function, it must be told what to do when a user logs in or out. This is done by calling the navigator.id.watch() function and supplying three parameters:

  1. The email address of the user currently logged into your site from this computer, or null if no one is logged in. For example, you might examine the browser's cookies to determine who is signed in.

  2. A function to invoke when an onlogin action is triggered. This function is passed a single parameter, an “identity assertion,” which must be verified.

  3. A function to invoke when an onlogout action is triggered. This function is not passed any parameters.

Note: You must always include both onlogin and onlogout when you call navigator.id.watch().

For example, if you currently think Bob is logged into your site, you might do this:

var currentUser = 'bob@example.com';
navigator.id.watch({
  loggedInUser: currentUser,
  onlogin: function(assertion) {
    // A user has logged in! Here you need to:
    // 1. Send the assertion to your backend for verification and to create a session.
    // 2. Update your UI.
    $.ajax({ /* <-- This example uses jQuery, but you can use whatever you'd like */
      type: 'POST',
      url: '/auth/login', // This is a URL on your website.
      data: {assertion: assertion},
      success: function(res, status, xhr) { window.location.reload(); },
      error: function(xhr, status, err) {
        navigator.id.logout();
        alert("Login failure: " + err);
      }
    });
  },
  onlogout: function() {
    // A user has logged out! Here you need to:
    // Tear down the user's session by redirecting the user or making a call to your backend.
    // Also, make sure loggedInUser will get set to null on the next page load.
    // (That's a literal JavaScript null. Not false, 0, or undefined. null.)
    $.ajax({
      type: 'POST',
      url: '/auth/logout', // This is a URL on your website.
      success: function(res, status, xhr) { window.location.reload(); },
      error: function(xhr, status, err) { alert("Logout failure: " + err); }
    });
  }
});

In this example, both onlogin and onlogout are implemented by making an asynchronous POST request to your site’s backend. The backend then logs the user in or out, usually by setting or deleting information in a session cookie. Then, if everything checks out, the page reloads to take into account the new login state.

Note that if the identity assertion can't be verified, you should call navigator.id.logout(): this has the effect of telling Persona that no one is currently logged in. If you don't do this, then Persona may immediately call onlogin again with the same assertion, and this can lead to an endless loop of failed logins.

You can, of course, use AJAX to implement this without reloading or redirecting, but that’s beyond the scope of this tutorial.

Here is another example, this time not using jQuery.

function simpleXhrSentinel(xhr) {
    return function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200){
                // reload page to reflect new login state
                window.location.reload();
              }
            else {
                navigator.id.logout();
                alert("XMLHttpRequest error: " + xhr.status); 
              } 
            } 
          } 
        }
function verifyAssertion(assertion) {
    // Your backend must return HTTP status code 200 to indicate successful
    // verification of user's email address and it must arrange for the binding
    // of currentUser to said address when the page is reloaded
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/xhr/sign-in", true);
    // see http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
    var param = "assertion="+assertion;
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", param.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.send(param); // for verification by your backend
    xhr.onreadystatechange = simpleXhrSentinel(xhr); }
function signoutUser() {
    // Your backend must return HTTP status code 200 to indicate successful
    // sign out (usually the resetting of one or more session variables) and
    // it must arrange for the binding of currentUser to 'null' when the page
    // is reloaded
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/xhr/sign-out", true);
    xhr.send(null);
    xhr.onreadystatechange = simpleXhrSentinel(xhr); }
// Go!
navigator.id.watch( {
    loggedInUser: currentUser,
         onlogin: verifyAssertion,
        onlogout: signoutUser } );

You must call navigator.id.watch() on every page with a login or logout button. To support Persona enhancements like automatic login and global logout for your users, you should call this function on every page of your site.

Persona will compare the email address you've passed into loggedInUser with its knowledge of whether a user is currently logged in, and who they are. If these don't match, it may automatically invoke onlogin or onlogout on page load.

 

Step 4: Verify the user’s credentials

Instead of passwords, Persona uses “identity assertions,” which are kind of like single-use, single-site passwords combined with the user’s email address. When a user wants to log in, your onlogin callback will be invoked with an assertion from that user. Before you can log them in, you must verify that the assertion is valid.

It’s extremely important that you verify the assertion on your server, and not in JavaScript running on the user’s browser, since that would be easy to forge. The example above handed off the assertion to the site’s backend by using jQuery’s $.ajax() helper to POST it to /auth/login.

Once your server has an assertion, how do you verify it? The easiest way is to use a helper service provided by Mozilla. Simply POST the assertion to https://verifier.login.persona.org/verify with two parameters:

  1. assertion: The identity assertion provided by the user.
  2. audience: The hostname and port of your website. You must hardcode this value in your backend; do not derive it from any data supplied by the user.

For example, if you’re example.com, you can use the command line to test an assertion with:

$ curl -d "assertion=<ASSERTION>&audience=https://example.com:443" "https://verifier.login.persona.org/verify"

If it’s valid, you’ll get a JSON response like this:

{
  "status": "okay",
  "email": "bob@eyedee.me",
  "audience": "https://example.com:443",
  "expires": 1308859352261,
  "issuer": "eyedee.me"
}

You can learn more about the verification service by reading The Verification Service API. An example /auth/login implementation, using Python, the Flask web framework, and the Requests HTTP library might look like this:

@app.route('/auth/login', methods=['POST'])
def login():
    # The request has to have an assertion for us to verify
    if 'assertion' not in request.form:
        abort(400)
    # Send the assertion to Mozilla's verifier service.
    data = {'assertion': request.form['assertion'], 'audience': 'https://example.com:443'}
    resp = requests.post('https://verifier.login.persona.org/verify', data=data, verify=True)
    # Did the verifier respond?
    if resp.ok:
        # Parse the response
        verification_data = resp.json()
        # Check if the assertion was valid
        if verification_data['status'] == 'okay':
            # Log the user in by setting a secure session cookie
            session.update({'email': verification_data['email']})
            return 'You are logged in'
    # Oops, something failed. Abort.
    abort(500)

For examples of how to use Persona in other languages, have a look at the cookbook.

The session management is probably very similar to your existing login system. The first big change is in verifying the user’s identity by checking an assertion instead of checking a password. The other big change is ensuring that the user’s email address is available for use as the loggedInUser parameter to navigator.id.watch().

Logout is simple: you just need to remove the user’s session cookie.

Step 5: Review best practices

Once everything works, and you’ve successfully logged into and out of your site, you should take a moment to review best practices for using Persona safely and securely.

If you're making a production site, have a look at the implementor's guide, where we've collected tips for adding the kind of features often needed in real-world login systems.

Lastly, don’t forget to sign up for the Persona notices mailing list so you’re notified of any security issues or backwards incompatible changes to the Persona API. The list is extremely low traffic: it’s only used to announce changes which may adversely impact your site.

Document Tags and Contributors

Tags: 
  • Persona
 Contributors to this page: Sheppy, rolfedh, wbamberg, wblock, bella1000, chrisdavidmills, syndbg, Juanninja, abubacar, kscarfone, albano_prendushi, baileylo, jswisher, p-d-q, kenrick95, Kara.Dawn, qbolec, Maroosko, timbray, Wraithan, ZZZWWW, fmarier, sushimako, ccarruitero, iffy, jacky.akram, InternetBountyHunters1, Callahad, Tibortio, mitchcan28, marcoscarpetta, n8chz, mariaangelicalozano, spoiledstar, sebyte, EricJohn2001, qwzjk, Brettz9, aking, dave_e, Asmo, DerekRhodes, sergiotapia, wouterw, Hoops, mlindgren, wbjohn, catherina, Gnat, artiskomedia, dhesinoiiz, atul, diiipuu99@gmail.com, ronjay
 Last updated by: Sheppy, Feb 14, 2017, 9:33:46 AM

  1. .htaccess ( hypertext access )
  2. <input> archive
  3. Add-ons
    1. Add-ons
    2. Firefox addons developer guide
    3. Interaction between privileged and non-privileged pages
    4. Tabbed browser
    5. bookmarks.export()
    6. bookmarks.import()
  4. Adding preferences to an extension
  5. An Interview With Douglas Bowman of Wired News
  6. Apps
    1. Apps
    2. App Development API Reference
    3. Designing Open Web Apps
    4. Graphics and UX
    5. Open web app architecture
    6. Tools and frameworks
    7. Validating web apps with the App Validator
  7. Archived Mozilla and build documentation
    1. Archived Mozilla and build documentation
    2. ActiveX Control for Hosting Netscape Plug-ins in IE
    3. Archived SpiderMonkey docs
    4. Autodial for Windows NT
    5. Automated testing tips and tricks
    6. Automatic Mozilla Configurator
    7. Automatically Handle Failed Asserts in Debug Builds
    8. BlackConnect
    9. Blackwood
    10. Bonsai
    11. Bookmark Keywords
    12. Building TransforMiiX standalone
    13. Chromeless
    14. Creating a Firefox sidebar extension
    15. Creating a Microsummary
    16. Creating a Mozilla Extension
    17. Creating a Release Tag
    18. Creating a Skin for Firefox/Getting Started
    19. Creating a Skin for Mozilla
    20. Creating a Skin for SeaMonkey 2.x
    21. Creating a hybrid CD
    22. Creating regular expressions for a microsummary generator
    23. DTrace
    24. Dehydra
    25. Developing New Mozilla Features
    26. Devmo 1.0 Launch Roadmap
    27. Download Manager improvements in Firefox 3
    28. Download Manager preferences
    29. Drag and Drop
    30. Embedding FAQ
    31. Embedding Mozilla in a Java Application using JavaXPCOM
    32. Error Console
    33. Exception logging in JavaScript
    34. Existing Content
    35. Extension Frequently Asked Questions
    36. Fighting Junk Mail with Netscape 7.1
    37. Firefox Sync
    38. Force RTL
    39. GRE
    40. Gecko Coding Help Wanted
    41. HTTP Class Overview
    42. Hacking wiki
    43. Help Viewer
    44. Helper Apps (and a bit of Save As)
    45. Hidden prefs
    46. How to Write and Land Nanojit Patches
    47. Introducing the Audio API extension
    48. Java in Firefox Extensions
    49. JavaScript crypto
    50. Jetpack
    51. Litmus tests
    52. Makefile.mozextension.2
    53. Microsummary topics
    54. Migrate apps from Internet Explorer to Mozilla
    55. Monitoring downloads
    56. Mozilla Application Framework
    57. Mozilla Crypto FAQ
    58. Mozilla Modules and Module Ownership
    59. Mozprocess
    60. Mozprofile
    61. Mozrunner
    62. Nanojit
    63. New Skin Notes
    64. Persona
    65. Plug-n-Hack
    66. Plugin Architecture
    67. Porting NSPR to Unix Platforms
    68. Priority Content
    69. Prism
    70. Proxy UI
    71. Remote XUL
    72. SXSW 2007 presentations
    73. Space Manager Detailed Design
    74. Space Manager High Level Design
    75. Standalone XPCOM
    76. Stress testing
    77. Structure of an installable bundle
    78. Supporting private browsing mode
    79. Table Cellmap
    80. Table Cellmap - Border Collapse
    81. Table Layout Regression Tests
    82. Table Layout Strategy
    83. Tamarin
    84. The Download Manager schema
    85. The life of an HTML HTTP request
    86. The new nsString class implementation (1999)
    87. TraceVis
    88. Treehydra
    89. URIScheme
    90. URIs and URLs
    91. Using Monotone With Mozilla CVS
    92. Using SVK With Mozilla CVS
    93. Using addresses of stack variables with NSPR threads on win16
    94. Venkman
    95. Video presentations
    96. Why Embed Gecko
    97. XML in Mozilla
    98. XPInstall
    99. XPJS Components Proposal
    100. XRE
    101. XTech 2005 Presentations
    102. XTech 2006 Presentations
    103. XUL Explorer
    104. XULRunner
    105. ant script to assemble an extension
    106. calICalendarView
    107. calICalendarViewController
    108. calIFileType
    109. xbDesignMode.js
  8. Archived open Web documentation
    1. Archived open Web documentation
    2. Browser Detection and Cross Browser Support
    3. Browser Feature Detection
    4. Displaying notifications (deprecated)
    5. E4X
    6. E4X Tutorial
    7. LiveConnect
    8. MSX Emulator (jsMSX)
    9. Old Proxy API
    10. Properly Using CSS and JavaScript in XHTML Documents
    11. Reference
    12. Scope Cheatsheet
    13. Server-Side JavaScript
    14. Sharp variables in JavaScript
    15. Standards-Compliant Authoring Tools
    16. Using JavaScript Generators in Firefox
    17. Window.importDialog()
    18. Writing JavaScript for XHTML
    19. XForms
    20. background-size
    21. forEach
  9. B2G OS
    1. B2G OS
    2. Automated Testing of B2G OS
    3. B2G OS APIs
    4. B2G OS add-ons
    5. B2G OS architecture
    6. B2G OS build prerequisites
    7. B2G OS phone guide
    8. Building B2G OS
    9. Building and installing B2G OS
    10. Building the B2G OS Simulator
    11. Choosing how to run Gaia or B2G
    12. Customization with the .userconfig file
    13. Debugging on Firefox OS
    14. Developer Mode
    15. Developing Firefox OS
    16. Firefox OS Simulator
    17. Firefox OS apps
    18. Firefox OS board guide
    19. Firefox OS developer release notes
    20. Firefox OS security
    21. Firefox OS usage tips
    22. Gaia
    23. Installing B2G OS on a mobile device
    24. Introduction to Firefox OS
    25. Mulet
    26. Open web apps quickstart
    27. Pandaboard
    28. PasscodeHelper Internals
    29. Porting B2G OS
    30. Preparing for your first B2G build
    31. Resources
    32. Running tests on Firefox OS: A guide for developers
    33. The B2G OS platform
    34. Troubleshooting B2G OS
    35. Using the App Manager
    36. Using the B2G emulators
    37. Web Bluetooth API (Firefox OS)
    38. Web Telephony API
    39. Web applications
  10. Beginner tutorials
    1. Beginner tutorials
    2. Creating reusable content with CSS and XBL
    3. Underscores in class and ID Names
    4. XML data
    5. XUL user interfaces
  11. Case Sensitivity in class and id Names
  12. Creating a dynamic status bar extension
  13. Creating a status bar extension
  14. Gecko Compatibility Handbook
  15. Getting the page URL in NPAPI plugin
  16. Index
  17. Inner-browsing extending the browser navigation paradigm
  18. Install.js
  19. JXON
  20. List of Former Mozilla-Based Applications
  21. List of Mozilla-Based Applications
  22. Localizing an extension
  23. MDN
    1. MDN
    2. Content kits
  24. MDN "meta-documentation" archive
    1. MDN "meta-documentation" archive
    2. Article page layout guide
    3. Blog posts to integrate into documentation
    4. Current events
    5. Custom CSS classes for MDN
    6. Design Document
    7. DevEdge
    8. Developer documentation process
    9. Disambiguation
    10. Documentation Wishlist
    11. Documentation planning and tracking
    12. Editing MDN pages
    13. Examples
    14. Existing Content/DOM in Mozilla
    15. External Redirects
    16. Finding the right place to document bugs
    17. Getting started as a new MDN contributor
    18. Landing page layout guide
    19. MDN content on WebPlatform.org
    20. MDN page layout guide
    21. MDN subproject list
    22. Needs Redirect
    23. Page types
    24. RecRoom documentation plan
    25. Remove in-content iframes
    26. Team status board
    27. Trello
    28. Using the Mozilla Developer Center
    29. Welcome to the Mozilla Developer Network
    30. Writing chrome code documentation plan
    31. Writing content
  25. MMgc
  26. Makefile - .mk files
  27. Marketplace
    1. Marketplace
    2. API
    3. Monetization
    4. Options
    5. Publishing
  28. Mozilla release FAQ
  29. Newsgroup summaries
    1. Newsgroup summaries
    2. Format
    3. Mozilla.dev.apps.firefox-2006-09-29
    4. Mozilla.dev.apps.firefox-2006-10-06
    5. mozilla-dev-accessibility
    6. mozilla-dev-apps-calendar
    7. mozilla-dev-apps-firefox
    8. mozilla-dev-apps-thunderbird
    9. mozilla-dev-builds
    10. mozilla-dev-embedding
    11. mozilla-dev-extensions
    12. mozilla-dev-i18n
    13. mozilla-dev-l10n
    14. mozilla-dev-planning
    15. mozilla-dev-platform
    16. mozilla-dev-quality
    17. mozilla-dev-security
    18. mozilla-dev-tech-js-engine
    19. mozilla-dev-tech-layout
    20. mozilla-dev-tech-xpcom
    21. mozilla-dev-tech-xul
    22. mozilla.dev.apps.calendar
    23. mozilla.dev.tech.js-engine
  30. Obsolete: XPCOM-based scripting for NPAPI plugins
  31. Plugins
    1. Plugins
    2. Adobe Flash
    3. External resources for plugin creation
    4. Logging Multi-Process Plugins
    5. Monitoring plugins
    6. Multi-process plugin architecture
    7. NPAPI plugin developer guide
    8. NPAPI plugin reference
    9. Samples and Test Cases
    10. Shipping a plugin as a Toolkit bundle
    11. Supporting private browsing in plugins
    12. The First Install Problem
    13. Writing a plugin for Mac OS X
    14. XEmbed Extension for Mozilla Plugins
  32. SAX
  33. Security
    1. Security
    2. Digital Signatures
    3. Encryption and Decryption
    4. Introduction to Public-Key Cryptography
    5. Introduction to SSL
    6. NSPR Release Engineering Guide
    7. SSL and TLS
  34. Solaris 10 Build Prerequisites
  35. Sunbird Theme Tutorial
  36. Table Reflow Internals
  37. Tamarin Tracing Build Documentation
  38. The Basics of Web Services
  39. Themes
    1. Themes
    2. Building a Theme
    3. Common Firefox theme issues and solutions
    4. Creating a Skin for Firefox
    5. Making sure your theme works with RTL locales
    6. Theme changes in Firefox 2
    7. Theme changes in Firefox 3
    8. Theme changes in Firefox 3.5
    9. Theme changes in Firefox 4
  40. Updating an extension to support multiple Mozilla applications
  41. Using IO Timeout And Interrupt On NT
  42. Using SSH to connect to CVS
  43. Using workers in extensions
  44. WebVR
    1. WebVR
    2. WebVR environment setup
  45. XQuery
  46. XUL Booster
  47. XUL Parser in Python