Python API

This part of the documentation describes the interfaces for using django-browserid.

Template Helpers

Template helpers are the functions used in your templates that output HTML for login and logout buttons, as well as the CSS and JS tags for making the buttons function and display correctly.

django_browserid.helpers.browserid_info()

Output the HTML for the info tag, which contains the arguments for navigator.id.request from the BROWSERID_REQUEST_ARGS setting. Should be called once at the top of the page just below the <body> tag.

django_browserid.helpers.browserid_login(text='Sign in', color=None, next=None, link_class='browserid-login persona-button', attrs=None, fallback_href='#')

Output the HTML for a BrowserID login link.

Parameters:
  • text – Text to use inside the link. Defaults to ‘Sign in’, which is not localized.
  • color

    Color to use for the login button; this will only work if you have included the default CSS provided by django_browserid.helpers.browserid_css().

    Supported colors are: ‘dark’, ‘blue’, and ‘orange’.

  • next – URL to redirect users to after they login from this link. Defaults to views.Verify.success_url.
  • link_class – CSS class for the link. Defaults to browserid-login persona-button.
  • attrs

    Dictionary of attributes to add to the link. Values here override those set by other arguments.

    If given a string, it is parsed as JSON and is expected to be an object.

  • fallback_href – Value to use for the href of the link. If the user has disabled JavaScript, the login link will bring them to this page, which can be used as a non-JavaScript login fallback.
django_browserid.helpers.browserid_logout(text='Sign out', next=None, link_class='browserid-logout', attrs=None)

Output the HTML for a BrowserID logout link.

Parameters:
  • text – Text to use inside the link. Defaults to ‘Sign out’, which is not localized.
  • next – URL to redirect users to after they logout from this link. Defaults to views.Logout.redirect_url.
  • link_class – CSS classes for the link. The classes will be appended to the default class browserid-logout.
  • attrs

    Dictionary of attributes to add to the link. Values here override those set by other arguments.

    If given a string, it is parsed as JSON and is expected to be an object.

django_browserid.helpers.browserid_js(include_shim=True)

Return <script> tags for the JavaScript required by the BrowserID login button. Requires use of the staticfiles app.

If the BROWSERID_AUTOLOGIN_ENABLED setting is True, an extra JavaScript file for mocking out Persona will be included, and the shim won’t be included regardless of the value of the include_shim setting.

Parameters:include_shim – A boolean that determines if the persona.org JavaScript shim is included in the output. Useful if you want to minify the button JavaScript using a library like django-compressor that can’t handle external JavaScript.
django_browserid.helpers.browserid_css()

Return <link> tag for the optional CSS included with django-browserid. Requires use of the staticfiles app.

Admin Site

Admin site integration allows you to support login via django-browserid on the Django built-in admin interface.

class django_browserid.admin.BrowserIDAdminSite(name='admin')

Support logging in to the admin interface via BrowserID.

include_password_form = False

If True, include the normal username and password form as well as the BrowserID button.

copy_registry(site)

Copy the ModelAdmins that have been registered on another site so that they are available on this site as well.

Useful when used with django.contrib.admin.autocomplete(), allowing you to copy the ModelAdmin entries registered with the default site, such as the User ModelAdmin. For example, in urls.py:

from django.contrib import admin
admin.autodiscover()

from django_browserid.admin import site as browserid_admin
browserid_admin.copy_registry(admin.site)

# To include: url(r'^admin/', include(browserid_admin.urls))
Parameters:site – Site to copy registry entries from.
django_browserid.admin.site

Global object for the common case. You can import this in admin.py and urls.py instead of django.contrib.admin.site.

Authentication Backends

There are a few different authentication backends to choose from depending on how you want to authenticate users.

class django_browserid.auth.BrowserIDBackend
get_verifier()

Create a verifier for verifying assertions. Uses a django_browserid.base.RemoteVerifier by default.

filter_users_by_email(email)

Return all users matching the specified email.

create_user(email)

Return object for a newly created user account.

is_valid_email(email)

Return True if the email address is ok to log in.

verify(assertion=None, audience=None, request=None, **kwargs)

Verify the given assertion and audience. See authenticate for accepted arguments.

authenticate(assertion=None, audience=None, request=None, **kwargs)

Authenticate a user by verifying a BrowserID assertion. Defers to the verifier returned by BrowserIDBackend.get_verifier() for verification.

You may either pass the request parameter to determine the audience from the request, or pass the audience parameter explicitly.

Parameters:
  • assertion – Assertion submitted by the user. This asserts that the user controls a specific email address.
  • audience – The audience to use when verifying the assertion; this prevents another site using an assertion for their site to login to yours. This value takes precedence over the audience pulled from the request parameter, if given.
  • request – The request that generated this authentication attempt. This is used to determine the audience to use during verification, using the django_browserid.base.get_audience() function. If the audience parameter is also passed, it will be used instead of the audience from the request.
  • kwargs – All remaining keyword arguments are passed to the verify function on the verifier.
class django_browserid.auth.LocalBrowserIDBackend

Bases: django_browserid.auth.BrowserIDBackend

BrowserID authentication backend that uses local verification instead of remote verification.

Views

django-browserid works primarily through AJAX requests to the views below in order to log users in and out and to send information required for the login process, such as a CSRF token.

class django_browserid.views.Verify(**kwargs)

Bases: django_browserid.views.JSONView

Send an assertion to the remote verification service, and log the user in upon success.

failure_url

URL to redirect users to when login fails. This uses the value of settings.LOGIN_REDIRECT_URL_FAILURE, and defaults to '/' if the setting doesn’t exist.

success_url

URL to redirect users to when login succeeds. This uses the value of settings.LOGIN_REDIRECT_URL, and defaults to '/' if the setting doesn’t exist.

login_success()

Log the user into the site.

login_failure()

Redirect the user to a login-failed page. By default a 403 is returned.

post(*args, **kwargs)

Send the given assertion to the remote verification service and, depending on the result, trigger login success or failure.

dispatch(request, *args, **kwargs)

Run some sanity checks on the request prior to dispatching it.

class django_browserid.views.Logout(**kwargs)

Bases: django_browserid.views.JSONView

redirect_url

URL to redirect users to post-login. Uses settings.LOGOUT_REDIRECT_URL and defaults to / if the setting isn’t found.

post(request)

Log the user out.

class django_browserid.views.CsrfToken(**kwargs)

Bases: django_browserid.views.JSONView

Fetch a CSRF token for the frontend JavaScript.

Signals

django_browserid.signals.user_created

Signal triggered when a user is automatically created during authentication.

Parameters:
  • sender – The function that created the user instance.
  • user – The user instance that was created.

Exceptions

exception django_browserid.base.BrowserIDException(exc)

Raised when there is an issue verifying an assertion.

exc = None

Original exception that caused this to be raised.

Verification

The verification classes allow you to verify if a user-provided assertion is valid according to the Identity Provider specified by the user’s email address. Generally you don’t have to use these directly, but they are available for sites with complex authentication needs.

class django_browserid.RemoteVerifier

Verifies BrowserID assertions using a remote verification service.

By default, this uses the Mozilla Persona service for remote verification.

verify(assertion, audience, **kwargs)

Verify an assertion using a remote verification service.

Parameters:
  • assertion – BrowserID assertion to verify.
  • audience – The protocol, hostname and port of your website. Used to confirm that the assertion was meant for your site and not for another site.
  • kwargs – Extra keyword arguments are passed on to requests.post to allow customization.
Returns:

VerificationResult

Raises:

BrowserIDException: Error connecting to the remote verification service, or error parsing the response received from the service.

class django_browserid.LocalVerifier(*args, **kwargs)

Verifies BrowserID assertions locally instead of using the remote verification service.

verify(assertion, audience, **kwargs)

Verify an assertion locally.

Parameters:
  • assertion – BrowserID assertion to verify.
  • audience – The protocol, hostname and port of your website. Used to confirm that the assertion was meant for your site and not for another site.
Returns:

VerificationResult

class django_browserid.MockVerifier(email, **kwargs)

Mock-verifies BrowserID assertions.

__init__(email, **kwargs)
Parameters:
  • email – Email address to include in successful verification result. If None, verify will return a failure result.
  • kwargs – Extra keyword arguments are used to update successful verification results. This allows for mocking attributes on the result, such as the issuer.
verify(assertion, audience, **kwargs)

Mock-verify an assertion. The return value is determined by the parameters given to the constructor.

class django_browserid.VerificationResult(response)

Result of an attempt to verify an assertion.

VerificationResult objects can be treated as booleans to test if the verification succeeded or not.

The fields returned by the remote verification service, such as email or issuer, are available as attributes if they were included in the response. For example, a failure result will raise an AttributeError if you try to access the email attribute.

expires

The expiration date of the assertion as a naive datetime.datetime in UTC.

django_browserid.get_audience(request)

Determine the audience to use for verification from the given request.

Relies on the BROWSERID_AUDIENCES setting, which is an explicit list of acceptable audiences for your site.

Returns:The first audience in BROWSERID_AUDIENCES that has the same origin as the request’s URL.
Raises:django.core.exceptions.ImproperlyConfigured: If BROWSERID_AUDIENCES isn’t defined, or if no matching audience could be found.